Samashki95 Samashki95 - 3 months ago 17
C Question

Bit- manipulation

I'm implementing a JPEG-Decoder and in one step I need to determine the sign of a value from a given number of bits

(positive if 1th bit = 1)
.
When the 1th bit is
0
then I have to get the two's complement from this value and additionaly add 1 to result.

I've have the following function to do this job:

#include <stdio.h> /* printf */
#include <string.h> /* strcat */
#include <stdlib.h> /* strtol */

typedef int bool;
#define true 1
#define false 0

int DetermineSign(int val, int nBits)
{
bool negative = val < (1<<(nBits-1));

if (negative)
{
// (-1 << (s)), makes the last bit a 1, so we have 1000,0000 for example for 8 bits

val = val + (-1 << (nBits)) + 1;
}

// Else its unsigned, just return
return val;
}


Could anyone explain please what does this expression
(-1 << (nBits))
do and how it works?
I know there is a comment from author to explain it, but I also tested it with the following function and it returns another result.

const char *byte_to_binary(int x)
{
static char b[9];
b[0] = '\0';

int z;
for (z = 128; z > 0; z >>= 1)
{
strcat(b, ((x & z) == z) ? "1" : "0");
}

return b;
}

int main(void)
{
char testValue = 0;

testValue = (-1 <<(testValue));

printf("%s\n", byte_to_binary(testValue)); // output 1111 1111 doesn't it has to be 1000 000?

return 0;
}


Thank you!

Answer

It replaces the right-most (least significant) ones with zeros:

  • -1 << 0 == 0xFFFFFFFF
  • -1 << 1 == 0xFFFFFFFE
  • -1 << 2 == 0xFFFFFFFC
  • -1 << 3 == 0xFFFFFFF8
  • -1 << 4 == 0xFFFFFFF0
  • ...