OK, so say I have a signed char with value -103:
char s_char = -103;
How does the computer store this char in bits? Is the first bit 0 because the char is negative? If so, would the computer store the char as 01100101, because 1100101 (base 2) in base 10 is 103?
And a second question: how can I access or test a single bit in the signed char? Would
s_char & (0x80 >> pos)
give me the value of the bit at position pos counting from the left?
Signed values are usually stored using Two’s Complement. http://en.wikipedia.org/wiki/Two%27s_complement
This essentially provides a signed bit which determines whether or not the number stored is negative or positive. If you’re using an 8-bit int for example, the range of possible signed numbers is -128 to 127. This breaks down to a series of 8 bits, for example, where the left-most bit represents a value of -128. The bits following ‘hold’ half the value as the bit to left, but are positive instead. An 8-bit number in binary form would look like this:
Since a
charis an integer type, it would be stored in the same way as a regular int would be. Acharwith the value of -103 would break down to something like this:If you want to test a single bit, you could use a mask. For example, if you wanted to test if the left most bit was set, you could do something like this:
This return true if the left-most bit was set to 1 in s_char, regardless of the other bits. I hope that helps!