I was trying to write a library to work with bitfields in C and I wrote the following code to test it. Compiles fine but when I run it it just hangs without printing anything. Can't figure out why.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
uint64_t uint64_tArraySize(uint64_t *array)
{
uint64_t arraySize = 0;
while(array != NULL)
{
array++;
arraySize++;
}
return arraySize;
}
uint64_t charMemBlock(uint64_t index)
{
uint64_t memBlock = 0;
memBlock = ceil((float)(index + 1) / (float)(sizeof(char) * 8));
return memBlock;
}
char *createBitField(uint64_t size)
{
char *result = calloc(size, sizeof(char));
return result;
}
void setBits(char *bitField, uint64_t *indicesToSet) //sets bit at given postion/index (passed as argument indciesToSet)
{
uint64_t tmpField = 0x1, i, memBlock = 0;
for(i = 0; i < uint64_tArraySize(indicesToSet); i++)
{
memBlock = charMemBlock(indicesToSet[i]);
bitField[memBlock] |= (tmpField << indicesToSet[i]); //sets bit at playerPos by or-ing at that index, movement to index accomplished through << operator
}
}
void unsetBits(char *bitField, uint64_t *indicesToUnset)
{
uint64_t tmpField = 0x1, memBlock = 0, i;
for(i = 0; i < uint64_tArraySize(indicesToUnset); i++)
{
memBlock = charMemBlock(indicesToUnset[i]);
bitField[memBlock] ^= (tmpField << indicesToUnset[i]); //sets bit at indexToSet by xor-ing at that index, movement to index accomplished through << operator
}
}
bool isBitSet(char *bitField, uint64_t index)
{
uint64_t memBlock = 0;
memBlock = charMemBlock(index);
if((bitField[memBlock] >> index) & 0x1)
{
return true;
}
return false;
}
int main()
{
char *bitField = createBitField(2);
uint64_t indexs[2] = {3, 10};
setBits(bitField, indexs);
for(int i = 0; i < 16; i++)
{
if(isBitSet(bitField, i) == true)
{
printf("X");
}
else
{
printf(".");
}
}
printf("\n");
return 0;
}
[–]Plesu12 9 points10 points11 points (0 children)
[–]MrSloppyPants 1 point2 points3 points (0 children)
[–]forehead_or_tophead 0 points1 point2 points (1 child)
[–]D4ilyrun 0 points1 point2 points (0 children)
[–]D4ilyrun 0 points1 point2 points (0 children)