0

I tried:

#include<stdio.h>

main()
{
    int a=10000;
    unsigned char cp1=0,cp2=0,cp3=0,cp4=0;

    cp1 = (a & 0xff000000) >> 24;
    cp2 = (a & 0x00ff0000) >> 16;
    cp3 = (a & 0x0000ff00) >>  8;
    cp4 = (a & 0x000000ff)      ;

    printf("%d %d %d %d\n",cp1,cp2,cp3,cp4);
}

My output is:

0 0 39 16

I found (39<<8) + 16=10000.

I could not understand cp3=(a & 0x0000ff00)>>8; ==39 how it is working?

I know 0xff=255, I want to know how the (&) operation and 0xff are working together and taking particular bits.

Can you teach me how it is working?

4
  • Using wrong format specifier invokes undefined behavior. Commented Jun 20, 2014 at 5:46
  • @OliCharlesworth; 7.21.6 P(9): If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. Commented Jun 20, 2014 at 5:50
  • 1
    @haccks: yup, didn't notice these were unsigned. Commented Jun 20, 2014 at 5:56
  • @haccks: If all values of an unsigned char can be represented by a signed int (which is usually the case), the arguments will be promoted to signed int which matches the conversion specifiers. Commented Jun 20, 2014 at 6:07

1 Answer 1

2
             a  = 0010 0111 0001 0000
        0xff00  = 1111 1111 0000 0000
   (a & 0xff00) = 0010 0111 0000 0000
(a & 0xff00)>>8 = 0000 0000 0010 0111  //shift the bits of above ANDing 8 times to right
0000 0000 0010 0111 = 39 in decimal
Sign up to request clarification or add additional context in comments.

2 Comments

okay friend thanks for your help. you said clear cut answer.thanks again :D
My pleasure. Btw welcome to our community I hope you've read FAQ, it's important to read this and enjoyed the Q&A on SO. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.