unsigned int print_bits(void* in_ptr, unsigned int in_bytes);
unsigned int fetch_byte(void* in_ptr, unsigned int byte_offset);

I got a little confused how the variables were laid out in C structs (dependent on architecture and compiler), so I wrote a simple function that prints out the raw bits from memory in a way that is easy to read and understand. Struct alignment occurs on a whim of the system.

I tried to make the function as user friendly as possible by including some options in the header file. You can toggle binary/hex mode or change the printing characters there. The second function is just there for convenience and curiosity.

Here is the repository: https://github.com/jongtao/bitprint


This function takes in a pointer in_ptr and prints out the bits from that memory location for in_bytes bytes. It also has some printing options that you can change in the header file. It returns the number of bytes printed. The width of the print varies according to your architecture though the system’s pointer size.


This function takes in a pointer in_ptr and and returns the value in the byte at in_ptr offset by in_bytes bytes.

Sample Output

Output from test program main.c

Figure 1. Output from test program main.c

In the sample, I created the struct below, set all the values to one, and passed its pointer to print_bits().

/* datatypes of varying sizes */
struct datatypes
  char a;
  short int b;
  int c;
  long int d;
  float e;
  double f;
  long double g;
  void* h;
}; /* struct test */


Written on the 24th of January in 2014