1

I'm doing some bit operations on a variable-length bit string.

I defined a function setBits(char *res, int x, int y) that should work on that bit string passed by the *res variable, given a x and y (just to mention, I'm trying to implement something like a Bloom filter using 8 bits per x):

void setBits(char *res, int x, int y)
{
  *res |= x << (y * 8)
}

E.g. given the following x-y-vectors {0,0} ; {0,1} ; {1,2} ; {2,3}, I expect a bit string like this (or vice-versa depending whether little- or big-endian, but that isn't important right now):

0000 0010 0000 0001 0000 0000 0000 0000

So the lowest 8 bits should come from {0,0}, the second 8 bits from {0,1}, the next 8 bits come from {1,2} and the last from {2,3}.

Unfortunately, and I don't seem to get the reason for that, setBits always returns only the last result (in this case i.e. the bit string from {2,3}). I debugged the code and realized that *res is always 0 - but why? What am I doing wrong? Is it that I chose char* that it doesn't work or am I completely missing something very stupid?

1 Answer 1

4

Assuming 8-bit chars, the maximum value you can store in *res is 0xff i.e. (1<<8)-1.

Consider what happens when you call setBits for x=1, y=1

x << (y * 8) == 1 << (1 * 8)
             == 1 << 8
             == 0x100

*res is an 8-bit value so can only store the bottom 8 bits of this calculation. For any non-zero value of y, the bits which can be stored in *res are guaranteed to be 0.

Sign up to request clarification or add additional context in comments.

8 Comments

Oh! So it is really the char*? What could I do then? The length of the bit-string should be variable. Pass a char[], instead?
Yea, why don't you try char[] which is a byte array and see
@navititious Sorry, I'll struggle to offer more specific advice. I'm not sure what you're trying to achieve and don't know what a Bloom filter is
Ok, so I understand that the maximum I can store in a char is limited by 2^8 bits; but actually I'm using the char* pointer only to point to some memory I calloc'ed beforehand such that there is enough space to do the operation from above. So in any case it is limited? char[] unfortunately did not help.
The idea behind Bloom filter is not that important here. What I'm really trying to do is to build the bit string like in the example above, where for each vector given ´{0,0} ; {0,1} ; {1,2} ; {2,3}´, the second value of the vector is used to get the position within the bit string and the first value is the value that should be inserted in the bit string.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.