Maker Pro
Maker Pro

Understanding C code

ed181

Dec 27, 2010
15
Joined
Dec 27, 2010
Messages
15
#define HIGH_BYTE(w) (unsigned char)((unsigned int)w >> 8)

Does anyone understand this line of code? I'm fairly new to C and i can't seem to grasp what this line means.

Thanks for any help in advance
 

(*steve*)

¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd
Moderator
Jan 21, 2010
25,510
Joined
Jan 21, 2010
Messages
25,510
This is the definition of a macro which casts w to an unsigned integer, right shifts it by 8 bits, and returns the lower 8 bits as a char.

Essentially it returns the next to lowest significant byte of w.

Note that this is NOT a function, the calculations are done in-line.

char c ;
c = HIGH_BYTE(0x4100);

would be the same as

char c;
c = 'A';

because 0x41 = 65 = 'A'
 

ed181

Dec 27, 2010
15
Joined
Dec 27, 2010
Messages
15
That's great, thanks for the excellent explanation. Now i need to figure out why on earth someone would want to do that :)
 

Harald Kapp

Moderator
Moderator
Nov 17, 2011
13,722
Joined
Nov 17, 2011
Messages
13,722
This is useful for w being a 16 bit (or more) variable where you want to access bits 8...15.
An exampel is text that is presented not as a string of 8 bit characters, but as a string of 16 (32, 64...) variables where each variable contains 2 (4, 8, ...) characters.
One will have to look at the source code where the macro is used to find out why it is used (what it does at that location in the code).
 
Top