Mwilliams03
Mwilliams03

Reputation: 301

C : confusion over a small piece of code - what is '&0x'?

I'm new to C, and I am trying to workout two things in this peace of code;

Thanks in advance!

static __u16 smile_bmp[] = {0x3C, 0x42, 0x95, 0xA1, 0xA1, 0x95, 0x42, 0x3C};

displayImage(smile_bmp,res, daddress, file);

int displayImage(__u16 bmp[], int res, int daddress, int file)
{
    int i;
    for(i=0; i<8; i++)
        {
         block[i] = (bmp[i]&0xfe) >>1 | (bmp[i]&0x01) << 7;
        }
    res = i2c_smbus_write_i2c_block_data(file, daddress, 16,
        (__u8 *)block);
    sleep(1);
}

Upvotes: 1

Views: 867

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490308

The expression: (bmp[i]&0xfe) >>1 | (bmp[i]&0x01) << 7 as a whole is really a rotation (aka circular shift) of the 8 least significant bits of bmp[i].

The bmp[i] & 0xfe part is taking the number in bmp[i] and masking off the lower bit (0xfe means "FE in hexadecimal", which translates to 11111110 in binary), so when you and the two together, it's setting the lowest bit to 0 without changing any of the others (well, any of the others among the 8 least significant -- given the bmp[i] is of type __u16, it apparently has 16 bits, so the upper 8 bits in the mask are also zeros, so they're set to zero in the result as well).

Likewise, the bmp[i] & 0x01 part is masking off all but the lowest bit. 0x01 is 00000001, so when you and this value with anything else, you retain the original value of the least significant bit, and set all the other bits to 0.

It's then shifting the first to the right one bit, and the second to the left by 7 bits, and then using a bitwise or to put the two pieces back together. The net result is that what started out as bit 0 is now bit 7, and all of the others are shifted to the right one place (the previous bit 7 is now bit 6, previous bit 6 is now bit 5, etc.)

As an aside, the names __u8 and __u16 are reserved for the implementation, so unless those are actually provided by the implementation, you have undefined behavior (i.e., you're not allowed to define those names in your code).

Upvotes: 8

simonc
simonc

Reputation: 42185

Its a bitwise AND of the variable (bmp[i]) on the left and a constant expressed as hexadecimal

Upvotes: 5

Related Questions