Mani92
Mani92

Reputation: 1

Extracting Bits and Shifting

I don't understand why the following code output is 0xffffffef,... instead of 0xef. Kindly help me understand this:

#include <stdio.h>
main()
{
    int i;
    int n = 4;
    char txBuff = 0;
    long Data_b = 0xABCDEF;
    int y = sizeof(txBuff);
    printf("%d\n",y);

    txBuff = (Data_b & 0xff);
    for(i=0; i<n; i++)
    {
        txBuff = (Data_b & 0xff);
        //  txBuff= txBuff & 0xff;
        Data_b = (Data_b >> 8);
        printf("txBuff[%d]=%x, Data_b=%x \n", i, txBuff, Data_b);
    }
}

output:

1
txBuff[0]=ffffffef, Data_b=abcd 
txBuff[1]=ffffffcd, Data_b=ab 
txBuff[2]=ffffffab, Data_b=0 
txBuff[3]=0, Data_b=0 

Upvotes: 0

Views: 58

Answers (2)

ensc
ensc

Reputation: 6994

Use unsigned types when doing bit operations!

in

    char txBuff = 0;
        ...
        txBuff = (Data_b & 0xff);

the txBuff can become negative and will be propagated to int in the printf() call.

Upvotes: 0

tadman
tadman

Reputation: 211740

You're printing with the wrong placeholders:

printf("txBuff[%d]=%hhx, Data_b=%lx \n",i,txBuff,Data_b);

When you interpret an argument incorrectly you're going to see all kinds of weird results.

Here %hhx means "hex dumped unsigned char" and %lx means "hex dumped unsigned long" as per the printf notation.

For what it's worth clang helpfully complains:

tbuff.c:17:60: warning: format specifies type 'unsigned int' but the argument has type 'long' [-Wformat]
             printf("txBuff[%d]=%x, Data_b=%x \n",i,txBuff,Data_b);
                                           ~~              ^~~~~~
                                           %lx

Upvotes: 1

Related Questions