pBlack
pBlack

Reputation: 102

C++ Bitwise Shift using a File Pointer

I'm reading through someone else's code and can't quite understand how it's working. Here's the three lines of code. I want to know what the value of w3 is:

int w1 = fgetc(fp) & 0xFF;
int w2 = fgetc(fp) & 0xFF;
int w3 = w1 + (w2 << 8);

I understand that fgetc() returns a character from a FILE* fp, but I'm getting confused when he's using the & operator on a character with the value 0xFF. Then using the bitwise shift operator on w2 and adding it to w1. I'm not sure if I should be expected a character or an integer. This is a code snippet from a program that reads binary data from a file, generates UV coordinates as output. But I'm less concerned with that, and more concerned with how the above code works.

Thanks in advance for any responses.

Upvotes: 2

Views: 609

Answers (2)

imreal
imreal

Reputation: 10348

What this int w1 = fgetc(fp) & 0xFF; does is to mask the received int into a single byte. (fgetc() returns an int after all)

What this w1 + (w2 << 8); does is to combine both bytes in to a single int. Probably trying to deserialize a previously serialized integer. (Not the best way of doing it if endianness is an issue)

Upvotes: 1

nneonneo
nneonneo

Reputation: 179382

The & 0xff ensures that the result is unsigned. Then, w1 + (w2 << 8) makes a 16-bit integer from the two bytes. In effect, this code snippet is reading in a little-endian two-byte integer.

Upvotes: 3

Related Questions