user198736
user198736

Reputation:

On a little-endian machine, how will bit operators work?

I have the following code that takes pixel values from a file. I am on a Intel macbook running OS X. I believe that is little-endian. I have the following code which I am using to determine if the least significant bit is set on the pixels. It compiles and runs, but I am not sure if by operations are really giving me the correct data.

 typedef struct {
    unsigned char blue;
    unsigned char green;
    unsigned char red;
 } pixel_t;

 pixel_t *pixels = malloc(((bmp->dib.bmp_bytesz/3)+1) * sizeof(*pixels));

 printf("%u", (pixels[i].red & 0x01));
 printf("%u", (pixels[i].green & 0x01));
 printf("%u", (pixels[i].blue & 0x01));

Upvotes: 1

Views: 169

Answers (3)

lsk
lsk

Reputation: 532

Jonathan has the right answer already...just adding an example.

Endianness describes how multi-byte data is stored in computer memory. It describes the location of the most significant byte (MSB) and least significant byte (LSB) of an address in memory. Big Endian: Stores MSB first i.e. left to right Little Endian: Stores LSB first i.e. right to left.

Example: How is 0x04030201 stored in memory?

Address     BE  LE
00000000    04  01
00000001    03  02
00000002    02  03
00000003    01  04

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182819

Endianess is an internal detail affecting how values are stored. It has no effect on how values are computed.

Upvotes: 5

Jonathan Leffler
Jonathan Leffler

Reputation: 754450

Little-endian and big-endian refers to the order of bytes (not bits, per se) in larger units (like short or int).

The bitwise operations are the same; the operations are giving you the least significant bit of the numbers in pixels[i].blue etc. If they are stored in char (or unsigned char or signed char), then there is no issue. If they are stored in int or short or something, then the byte that is being addressed will be different depending on whether the machine is big-endian or little-endian, but it is still the least significant bit of the number on the platform.

Upvotes: 7

Related Questions