0

I have a short variable (16 bits) and an index (unsigned char). I need a macro that returns the indexth in my variable data. This is what I got:

#define GETBIT(data, index) data & 1 << index

And how I use it:

unsigned char i;
short * twobytes = (short *) calloc(1, sizeof(short));
twobytes =  ((char * )buffer + *currentIndex);
while (codeLength != 0)
{
    i = GETBIT(code, codeLength--);
    *twobytes = SETBIT(*twobytes, *currentBitIndex, i);
    (*currentBitIndex)++;
    if (*currentBitIndex == 8) {
        (*currentIndex)++;
        (*currentBitIndex) %= 8;
    }
}

For some reason i always equals to 0 in my test cases, where it sometimes should equal 1.

What am I doing wrong and how should I fix it?

Thanks.

shoham
  • 792
  • 2
  • 12
  • 30

2 Answers2

0

Nevermind, thanks, instead of codeLength-- I should've done --codeLength.

shoham
  • 792
  • 2
  • 12
  • 30
0

Example:

$ cat qq.c 
#include <stdio.h>

#define GETBIT(data, index) ((data & (1 << index)) == 0 ? 0 : 1)

int main() {
    const int x = 14;
    int i;
    for (i = 0; i < 32; i++) {
        printf("%d ", GETBIT(x, i));
    }
    printf("\n");
    return 0;
}

Run:

$ gcc -Wall qq.c && ./a.out 
0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
paq
  • 180
  • 6
  • `#define GETBIT(data, index) (((uintmax_t)(data) >> (index)) & 1)` is a little more general and a little simpler. If you are sure that the `data` is never any larger than `int`, then `unsigned` instead of `uintmax_t`. It's generally worth avoiding shifts of signed values ! –  Jul 16 '14 at 00:07
  • http://stackoverflow.com/a/4009954/2557000 (excerpt 6.5.7/4). But, of course, bitwise operations require to be very careful :) – paq Jul 16 '14 at 10:16