I am learning c. As an experiment I am trying to implement 128-bit addition and multiplication.
I want to do this using a void pointer as follows:
void* x = malloc(16);
memset(x, 0, 16);
Is it possible to read and write the ith bit of x? I understand how to do this using bitwise operations on standard data types but the compiler complains about invalid operands when I try and use bitwise operations on a void pointer. In general, I am interested in whether it is possible to malloc an arbitraryly sized block of memory and then manipulated each individual bit in c?
The C standard is surprisingly (although logically) inflexible when it comes to casting of pointer types, although you can cast the result of malloc to any pointer type you want.
In order to perform bit and byte analsysis, a safe type to use is char* or unsigned char*:
unsigned char* x = malloc(16);
(I'd always pick the unsigned char since some platforms have a 1's complement signed char type which, crudely put, is a pain in the neck).
Then you can use pointer arithmetic on x to manipulate the memory block on a byte by byte basis. Note that the standard states that sizeof(char) and sizeof(unsigned char) is 1, so pointer arithmetic on such a type will traverse the entire memory block without omitting any bits of it.
As for examining bit by bit, the standards-defined CHAR_BIT will tell you how many bits there are in a byte. (It's normally 8 but it would be unwise to assume that.)
Finally, don't forget to call free(x) at some point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With