Two's complement: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
m (J)
Line 52: Line 52:
a = -a;</lang>
a = -a;</lang>


=={{header|J}}==
<lang J> -3
_3</lang>
=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
===8-Bit===
===8-Bit===

Revision as of 00:39, 24 July 2022

Task
Two's complement
You are encouraged to solve this task according to the task description, using any language you may know.

Two's complement is an important concept in representing negative numbers. To turn a positive integer negative, flip the bits and add one.


Task

Show how to calculate the two's complement of an integer. (It doesn't necessarily need to be a 32 bit integer.)


6502 Assembly

8-Bit

<lang 6502asm>LDA #%01010101 EOR #255 CLC ADC #1 ;result: #%10101011</lang>

16-bit

<lang 6502asm>myVar equ $20

LDA #3 STA myVar LDA #0 STA myVar+1 ;equivalent C: uint16_t myVar = 3;

negate: LDA myVar+1 EOR #255 STA myVar+1

LDA myVar EOR #255 STA myVar CLC ADC #1 STA myVar

this handles the case if we started with something where the low byte was zero.

LDA myVar+1 ADC #0 STA myVar+1</lang>

8086 Assembly

<lang asm>mov al,17 neg al ;8-bit mov bx,4C00h neg bx ;16-bit</lang>


C

<lang C>int a = 3; a = -a;</lang>

J

<lang J> -3 _3</lang>

Z80 Assembly

8-Bit

Zilog Z80

<lang z80>ld a,%00001111 neg ;returns %11110001 in a</lang>

Game Boy <lang z80>ld a,%00001111 cpl ;game boy doesn't have NEG but it has CPL which flips all the bits. inc a ;returns %11110001 in a</lang>

16 Bit

NEG and CPL only work on the accumulator A. The following can be written to work with BC, DE, HL, IX, or IY. <lang z80>xor a ;ld a,0 sub c ld c,a sbc a ;loads &FF into A if "sub c" set the carry (borrow) flag. Otherwise, a remains zero. sub b ld b,a</lang>