简体   繁体   中英

bit shift in c language

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 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?

             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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM