Exchange nibbles using bitfields

hacker_compHere’s an way of exchanging the 2 nibbles of a character using bitfields in C. The idea is to change the value 0xab to 0xba in-place demonstrating how bitfields work.┬áThis is an alternative to using bitwise shift operators which is far more elegant.


struct bits {
        unsigned char nibbleA : 4;
        unsigned char nibbleB : 4;

int main()
        unsigned char val = 0b10100101;
        printf("sizeof struct bits: %ld byte(s)\n", sizeof(struct bits));                   
        printf("Initial value: %x\n", val);

        struct bits *ptr = (struct bits *)&val;

        ptr->nibbleA += ptr-> nibbleB;
        ptr->nibbleB = ptr->nibbleA - ptr-> nibbleB;
        ptr->nibbleA -= ptr-> nibbleB;

#if 0
        /* Common procedure */
        val = (val << 4) | (val >> 4);

        printf("Final value: %x\n", val);
        return 0;

Compile and run:

$ gcc -o test test.c
$ ./test
sizeof struct bits: 1 byte(s)
Initial value: a5
Final value: 5a


Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s