I am a beginner in C and During Programming I have found this code about bitwise addition
#define WORD_FROM_BUF(WRD) ((((unsigned char *)(WRD))[0]<<8)|((unsigned char *)(WRD))[1])
I have tried to modify this code to this form
#define WORD_FROM_BUF(WRD) (((unsigned char *)(WRD[0])<<8)|((unsigned char *)(WRD[1]))
But the results were different What is the difference between these two lines? and why the results are different?
CodePudding user response:
(unsigned char *)(WRD)
takes the pointer(?) WRD
and converts it into a pointer to bytes. Indexing that byte-pointer with [0]
gets the first byte from the buffer. When combining that with the next byte, you get a two-byte value.
(unsigned char *)(WRD[0])
takes the first word(?) from the buffer and turns that word into a pointer. Totally different, and very likely totally wrong as shifting the pointer << 8
make little sense.
Then WRD[1]
picks up the second word from the buffer, not the second byte.