n=int(input())

def Bin(n):

if n>=2:

Bin(n//2)

print(n%2, end=“”)

else:

Bin(n)

idk how to integer negative into binary code, help pls

n=int(input())

def Bin(n):

if n>=2:

Bin(n//2)

print(n%2, end=“”)

else:

Bin(n)

idk how to integer negative into binary code, help pls

It’s most usual to represent negative numbers in binary as two’s-complement, but you haven’t said whether that’s the desired format. If it’s not, then just represent a negative binary number in the same way as a negative decimal number, namely, as a minus sign followed by the positive value.

Not too sure if this will help…

If you consider 8-bits (1-Byte), this can represent decimal values between 0 and 255. But, if the most significant bit is used as a ‘parity bit’ the decimal values are -128 to +127. Notice the the range does not change and the bits are still `00000000`

to `11111111`

. The only thing that changes is how we choose to interpret the bit pattern.

The math for four bits (most significant bit being used as a ‘parity bit’) is thus:

```
0 0 0 1: 1 = 2^0
0 0 1 0: 2 = 2^1
0 0 1 1: 3 = (2^1) + (2^0)
0 1 0 0: 4 = 2^2
0 1 0 1: 5 = (2^2) + (2^0)
0 1 1 0: 6 = (2^2) + (2^1)
0 1 1 1: 7 = (2^2) + (2^1) + (2^0)
1 0 0 0: -8 = -2^3
1 0 0 1: -7 = (-2^3) + (2^0)
1 0 1 0: -6 = (-2^3) + (2^1)
1 0 1 1: -5 = (-2^3) + (2^1) + (2^0)
1 1 0 0: -4 = (-2^3) + (2^2)
1 1 0 1: -3 = (-2^3) + (2^2) + (2^0)
1 1 1 0: -2 = (-2^3) + (2^2) + (2^1)
1 1 1 1: -1 = (-2^3) + (2^2) + (2^1) + (2^0)
```

That can be extended to as many bits as you need to work with. I’ve used four bits only, for the sake of brevity.

1 Like

@rob42: The most significant bit would be the sign bit, not the parity bit. Parity is something different.

1 Like

Yes, thanks. I’m not too sure where I picked that terminology up from (maybe a tutor) in relation to BCD. I know it’s used (or was used) in data transmission protocols: I’m old enough to remember RS232 connections and the 'parity check` that was needed.