Arithmetic and boolean operation to make 0 to 1, and everything else to 0

124 Views Asked by At

I have a 16 bit binary number $x$, and I want to perform on it a series of operations that will result in: if $x = 0000000000000000$ then $f(x) = 1111111111111111$, and if $x \neq 0000000000000000$, then $f(x) = 0000000000000000$.

Here are the operations I have ($y$ is any 16-bit number) :

  1. Binary 16-bit addition $(x+y)$, that ignores overflow beyond the 16-bit.
  2. Binary 16-bit subtraction
  3. Bitwise 16-bit AND $(x\;\&\;y)$: for example $1111111111111111\;\&\; 1111111111111000 = 1111111111111000$
  4. Bitwise 16-bit OR
  5. Bitwise 16-bit NOT $(!x)$, for example $!(1111111111111000) = 0000000000000111$

These restraints are because those are the operations my ALU supports. Even If you have a function that requires more than the above operations, please share it, and I will figure out how to do it.

Thanks

1

There are 1 best solutions below

3
On

As a first step, here is a function is0(x) that returns 1000000000000000 if x is zero and 0 if x is non-zero.

y = x - 1                    //is 1??????????????? if x=0 or x > 1000000000000000
z = (!x) & 1000000000000000  //inverts the highest bit of x, remove all other
w = y & z                   
return w

This is independent of any carry in the ALU, and already gives a non-zero result if x=0 and a zero otherwise.

Now the final tricky function iszero(x)that uses carry arithmetic

y = is0(x)
add y,y ->(z, carry)   //z is always zero, carry set if x is 0
sbc z,z -> w           //1111111111111111 if x is zero, 0 otherwise
return w

The function was implemented and fully tested on a x86 system, here the code with Intel syntax

mov ax,[x]
mov bx,ax
not bx
sub ax,1
and ax,bx
mov bx,0x8000
and ax,bx
add ax,ax
sbb ax,ax
mov [w],ax