Hey guys I am looking to generate a random 4 bit number in C and then shift the bits so I can access each bit. Could I see an example of how to do that?
This is simple stuff. Use random() from a standard library, in a cycle read modulo of 2, this will tell you what the rightmost bit is, then shift right by one, repeat until out of bits to read.
Since memory is byte-addressed you can't address something smaller than a byte. So you don't have a 4-bit pre-made data type (also called a nibble). But you can easily achieve this by using a struct or union and bit fields:
struct A {
unsigned nibble1 : 4;
unsigned nibble2 : 4;
};
In order to access the single bits of the binary rapresentation of let's say an int we use a bit mask and the logical &. For example this prints the binary rapresentation of an int:
/* Bit print an int expression. */
#include <limits.h>
void bit_print(int a)
{
int i;
int n = sizeof(int) * CHAR_BIT;
int mask = 1 << (n-1);
for (i = 1; i <= n; i++) {
putchar(((a & mask) == 0) ? '0' : '1');
a <<= 1;
if (i % CHAR_BIT == 0 && i < n)
putchar(' ');
}
}