2 byte short into 2 byte string in C?
Domanda
Any way to convert a a 2 byte short (normal short) into just a 2 byte string (char*) after using htons on that short. The thing is that the htons method returns an int (4 bytes), how do I put it into a 2 byte string ???
Note: I need to be able to use ntohs on the result to get the original value.
Thanks in advice :D
Soluzione
Ahm, how do you say htons returns a 4-byte integer, on my linux, htons has the prototype of
uint16_t htons(uint16_t hostshort);
Thus you can do
uint16_t value;
value = htons(hostshort);
char *bytes = &value;
// now the first 2 bytes pointed to by "bytes" are the value in network byte order
Which means the return value is just 2 bytes.
Then I think it is quaranteed after htons that such bit representation on the returned value is such that the first byte of the value (((unsigned char *)value)[0]) is the most significant, and the second the least significant.
Altri suggerimenti
short i;
// ...
char s [3];
s [0] = (i >> 8) & 0xFF;
s [1] = i & 0xFF;
s [2] = '\0';
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow