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

Leave a Reply

Your email address will not be published. Required fields are marked *