Home > Back-end >  Bitwise Shift to MSB in One Byte Added to Itself
Bitwise Shift to MSB in One Byte Added to Itself

Time:12-25

I am reading a book, "Network Programming with C" by Lewis Van Winkle and I discovered a line of code in Chapter 5, page 153 that I do not understand the value of. The context is around DNS resolutions through a header. What is the value or practical application of the following code:

/* msg[] is unsigned char*/
const int qdcount = (msg[4] << 8)   msg[5]

I understand that int is a wider type than char but why is the extra precision of value, for hardware interfacing at the firmware level if you choose to go deeper or what? To me, it appears that the grouped object would resolve to a value of the external object since shifting 8 bits is equal to one byte thus making it effectively just a product of itself with two, but why even use this method instead of just using:

2 * msg[5]

Not sure where to start looking for a solution because the problem is not clear.

CodePudding user response:

msg[4] contains the most significant eight bits out of a 16-bit number. msg[5] contains the least significant eight bits.

msg[4] << 8 takes byte containing the most significant of 16 and shifts it left eight positions so they are in the positions of the most significant eight bits of 16. Then msg[5] puts the byte containing the least significant bits in the low eight bits of the 16. This reconstructs the 16-bit number that msg[4] and msg[5] came from.

msg[4] and msg[5] generally could not be loaded in a single load of a 16-bit integer because C code may execute in implementations in which the more significant byte is in the higher-addressed byte, not the lower-addressed byte and also because of type and aliasing rules in the C standard.

  • Related