September 2, 2016

C operator priority: Shift is lesser than +/-

int main(){
        unsigned char buf[2];
        int x;
        buf[0]=0xF0;
        buf[1]=0xA5;
        x=buf[0]<<8+buf[1];
        printf("x=%08x\n",x);
}


The above code returns wrong values (not 0xF0A5). You need to add parenthesis around the shift operator: 

x=(buf[0]<<8)+buf[1];

Or use multiplication

x=buf[0]*256+buf[1];

No comments:

Post a Comment