Covert char[2] to uint16_t for socket programming?

260 Views Asked by At

I am writing a tftp client. But when i convert the block number as follows:

uint16_t blockN = buffer[2]<<8 | buffer[3];

after 127, i am getting 65408 as blockN. What might be the problem here?

Thank you for your answers.

2

There are 2 best solutions below

0
On BEST ANSWER

I solved by doing uint16_t blockN = buffer[2]<<8 | (buffer[3]&0xFF);

1
On

You have to change the type of buffer array from an array of char to an array of unsigned char, otherwise buffer[2] will be promoted to int and sign extension will occur. On most platforms char type is a signed type.