2

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

Onica Radu
  • 183
  • 2
  • 4
  • 11
  • Do you want to convert a `short` or an `int`? `int` is mostly 4 bytes nowadays. – JohnB Oct 16 '12 at 19:11
  • i figured that htons just returns another short, so the real problem is just converting a short into a 2 byte string – Onica Radu Oct 16 '12 at 19:45

2 Answers2

3

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.

  • My bad on that its the same for me, but now the question is how do i get that into a string of only 2 bytes. I tried using sprintf but imagine that htons return 2000 for example how can I store this into a string of 2 bytes ?? :( – Onica Radu Oct 16 '12 at 19:44
2
short i;
// ...
char s [3];
s [0] = (i >> 8) & 0xFF;
s [1] = i & 0xFF;
s [2] = '\0';
JohnB
  • 13,315
  • 4
  • 38
  • 65
  • Can you please explain exactly what are you putting in s[0] and 0xFF is NULL right ?? :( – Onica Radu Oct 16 '12 at 19:36
  • (i>>8) shifts the top 8 bits of i by 8, so therefore to the bottom 8 bits, with & 0xFF masking out the top 8 bits. i & 0xFF stores the bottom 8 bits of i in s[1]. Then a null for s[2] – DaV Oct 16 '12 at 19:49
  • I'd first cast `i` to `unsigned (short)` to avoid implementation-defined behavior of `>>` on negative integers. – Alexey Frunze Oct 16 '12 at 20:34
  • Yes, probably you're right. Arithmetic and binary shift should, however, differ only with respect to the "newly inserted" bits, which for a negative number are 1 for an arithmetic right-shift and 0 for a binary one. Isn't this standardized? – JohnB Oct 17 '12 at 07:06
  • shouldn't matter in this case; any sign bits are outside the 0xFF mask. – Antti Haapala -- Слава Україні Oct 17 '12 at 21:49