Reputation: 310
Suppose I am dealing with 4 bit operations. So if I encounter an binary digit say
1111
then what should I infer ? Is it -1 or 15 ?
Upvotes: 3
Views: 174
Reputation: 399833
"That depends".
The bits are (in this case) encoding a number, but you have to know which kind of number (signed or unsigned, integer, fixed-point or float) in order to interpret the encoded bits.
If the number is supposed to be signed in two's complement, then the proper interpretation is -1, if it's unsigned then it's 15.
It's not possible to decide from those four bits alone, it's simply not enough information.
This of course is true for a "full-sized" value too, it could be an int
or an unsigned int
and you have to know that in order to correctly interpret the bits.
Update: If you know that your number is supposed to be signed, the easiest way to deal with it (assuming C, which generally doesn't have a signed 4-bit integer type) is to sign-extend it into a usable form.
Sign-extending merely involves taking the most significant bit of the fewer-bits number, and repeating it to the left up to (and including) the most significant bit of the target one.
So in your case, you have 0xf
, whose top bit is 1. Extending to an int8_t
, we get:
const int8_t number = 0xff;
Which is -1.
There is no built-in way to do this sign-extension from an arbitrary few-bits number, since C can't natively deal with those.
Here's a naive approach:
// Sign-extend a n-bit number into 32 bits.
int32_t extend(uint32_t bits, size_t n)
{
const bool top = bits & ((uint32_t) 1 << (n - 1));
if (top)
{
for (size_t i = n; i < 32; ++i)
bits |= 1 << i;
}
return bits;
}
If you call the above with your number:
printf("%d\n", (int) extend(0xf, 4));
it prints -1
.
Upvotes: 2