Reputation: 97
In memory 128 will be stored as 10000000
. Where should I place the sign bit here since whole 1 byte is occupied by number 128 if i store -128 in byte datatype?
Can you please explain me?
Upvotes: 3
Views: 1346
Reputation: 225227
Signed integers are typically represented in two's complement. This means that for a given positive number, the corresponding negative number is obtained by inverting all bits then adding 1.
A negative number in two's complement will have the high order bit set. This bit becomes the sign bit.
So for a number occupying a single byte, 11111111
represents -1, 11111110
represents -2, and so forth, all the way to 10000000
which represents -128. On the high end, 01111111
represents 127.
This means that a 1 byte signed integer cannot store the value 128. If you had a 1 byte unsigned integer then 10000000
would be 128 but then it could not hold any negative numbers.
Upvotes: 10
Reputation: 787
A single byte means 8 bits, which mean you can choose from 2^8 = 256 values. In C representation for signed char (or signed integer of 1 byte) teh values chosen were from [-128, 127] including both extremes
Upvotes: 2
Reputation: 498
you could cast to unsigned char, like
char s128 = (char)128;
if((unsigned char)s128==128){
printf("true\n");
}
Upvotes: 0