# bit patterns of negtive numbers?

Printable View

• 11-08-2004
chunlee
bit patterns of negtive numbers?
hi there:

i am just learning more about data types and thought i will write a short code to see the bit patterns of signed variable, in this case a char.

i know that the first bit of signed data types is called sign bit, so i suspected to see something like:

decimal 1 -> 00000001
decimal -1 -> 10000001

the left most bit being the sign bit.

however, in the code i worte i got:

decimal value -> -1 :: bit pattern -> 11111111
decimal value -> 1 :: bit pattern -> 00000001

and it seems that -128 comes after +127 as:

decimal value -> 127 :: bit pattern -> 01111111
decimal value -> -128 :: bit pattern -> 10000000

my question is that, if this is the correct bit representation of signed char, how does negative numbers are convereted into bit patterns? of course, it could be something wrong in the code i wrote, my code are as below:

main()
{
char string[9];
int i;
char test;
unsigned char MASK;

for(test = -128; test<127; test++)
{
MASK = 1<<7;
for(i=0; i<8; i++)
{
sprintf(string+i, "%d", (test & MASK) ? 1 : 0);
MASK>>=1;
}
string[8] = (char)NULL;
printf("decimal value -> %d :: bit pattern -> %s\n", test, string);
}
}

many thanks

CHUN
• 11-08-2004
hk_mp5kpdw
Negation is accomplished using something called two's complement. Do a search on it to find out more but basically to convert a value from positive to negative, you negate all the bits (zeros become ones and ones become zeros) and then you add 1. So, if 1 is 00000001 then to negate it we first takes its ones complement which is 11111110 and then add 1 to get the two's complement which is 11111111. 127 is 01111111 so -127 is 10000000 (ones complement) and add 1 to get the final answer of 10000001. -128 is 1 less than -127 so take 10000001 and subtract 1 and you get 10000000.
• 11-08-2004
Thantos
Code Tags

The reason for the twos complement is so you can add signed numbers and get the correct result.

1 + -1 = 0

Code:

``` 00000001 +11111111 ---------- 100000000```
But you only take the least signficant bits (in this case 8) so you get 00000000
• 11-08-2004
chunlee
thanks, i will look into it in more depth.

cheers

CHUN
• 11-08-2004
Dave_Sinkula
Quote:

Originally Posted by chunlee
i am just learning more about data types and thought i will write a short code to see the bit patterns of signed variable, in this case a char.

i know that the first bit of signed data types is called sign bit, so i suspected to see something like:

decimal 1 -> 00000001
decimal -1 -> 10000001

There are three possible representations of signed integral types in C:
• sign and magnitude
• two's complement
• one's complement
A brief description is here. Use Google for more.