Covert char[2] to uint16_t for socket programming?

234 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 answers

0
ahmetsarias On BEST ANSWER

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

1
ouah 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.