Saturday 23 March 2013

OOP344 Week 11: Bit Dump Function

The following is a function that prints the address of a pointer in bits with formatting (a space after every 4th binary digit):

#include <cstdio>

void bitDump(void* address, unsigned int sizeInBytes){
    unsigned char* c = (unsigned char*)address;
    int i;
    for (i = 0; i < sizeInBytes; i++){
        unsigned int hex = (int)c[i];
        unsigned int m = 1 << sizeof(hex)*8-1;
        int j;
        for(j = 0; m; j++){ 
            if ((j+ 1)% 5 == 0){
                printf(" ");
            }
            else {
                printf("%d", (hex & m)&&1);
                m = m >> 1;
            }
        }
        printf(" ");
    } 
}
int main(){
    long double ld = 12345.123456;
    bitDump(&ld, sizeof(ld)); // print the bit pattern (cool if formatted)
    return 0;
}

No comments:

Post a Comment