简体   繁体   English

2字节短到2字节字符串在C中?

[英]2 byte short into 2 byte string in C?

Any way to convert aa 2 byte short (normal short) into just a 2 byte string (char*) after using htons on that short. 在短字节上使用htons之后,将2字节短(普通短)转换为2字节字符串(char *)的任何方法。 The thing is that the htons method returns an int (4 bytes), how do I put it into a 2 byte string ??? 问题是htons方法返回一个int(4个字节),如何将其放入2个字节的字符串中?

Note: I need to be able to use ntohs on the result to get the original value. 注意:我需要能够在结果上使用ntohs以获得原始值。

Thanks in advice :D 感谢您的建议:D

Ahm, how do you say htons returns a 4-byte integer, on my linux, htons has the prototype of Ahm,怎么说怎么说呢?htons返回一个4字节的整数,在我的Linux上,htons具有以下原型:

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. 这意味着返回值仅为2个字节。

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. 然后,我认为在htons之后被隔离的是,返回值的这种位表示形式是,值的第一个字节(((unsigned char *)value)[0])最高,而第二字节最低。

short i;
// ...
char s [3];
s [0] = (i >> 8) & 0xFF;
s [1] = i & 0xFF;
s [2] = '\0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM