Reputation: 41
I am trying to speed up a program with bitshifts. For doing that I am allocating some space for the bits to store.
Now I have to set the bit in the middle to 1. So for example I want:
00000010000000
to be in my memory. (The length is defined by the user on run-time).
Here is my Code:
int *state = malloc(b); // Where 'b' is a user defnied value
*state |= (1 << b);
But when I print out the bits I get something like this (for b = 10):
000000000010000000000000000000000000000000100000000000000000000000000000001000000000000000000000000
So it keeps placing many 1's instead of one 1 in the middle.
What am I doing wrong here?
I belived it has to do with me using int, maybe the workaround would be not using int. But I don't know how to allocate a bitarray in another way.
This is how I print the bits (requestet in comments):
64 for(i =0; i < b; i++){
65 printf("%d", ((*state & (1 << i)) >> i));
66 }
Upvotes: 0
Views: 147
Reputation: 22457
You are mixing up bits and bytes.
To allocate b bits, you need
int *state = malloc(sizeof(int)*((b+sizeof(int)-1)/sizeof(int))); // Where 'b' is a user defnied value
To set a bit in this array, decompose into int position and bit position:
state[b/sizeof(int)] |= (1 << (b % sizeof(int)));
If you are going to work with single bits, it might be easier to use unsigned char
instead of int
as the base array.
Edit: just changed the allocation from (b+sizeof(int)-1)/sizeof(int)
-- this calculates the required byte size. Of course you need to allocate room for int sized members, so the allocated memory size is the number of bytes times sizeof(int)
.
Upvotes: 6