Two's complement: Difference between revisions
Puppydrum64 (talk | contribs) (Created page with "{{task|Basic language learning}} Category:Simple wp:Two's_complement Two's complement is an important concept in representing negative numbers. To turn a positive int...") |
Puppydrum64 (talk | contribs) m (fixed wiki tag) |
||
Line 2: | Line 2: | ||
[[Category:Simple]] |
[[Category:Simple]] |
||
[[wp:Two's_complement |
[[wp:Two's_complement|Two's complement]] is an important concept in representing negative numbers. To turn a positive integer negative, flip the bits and add one. |
||
;Task |
;Task |
Revision as of 23:22, 23 July 2022
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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. If the technique is different depending on the size of the integer, give an example of each.
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>