请注意,这不是作业,我在开始这个新线程之前搜索过。我得到了Store an int in a char array?编码,将整数解码为字符数组
我正在寻找答案,但没有得到任何满意的答案在上述线程。
这是我的要求:我想要编码我的数据(比如一个整数)在一个字节数组中,然后通过网络传输,然后在另一端解码并处理它。
这里的编码部分:
const int MAX=5;
uint32_t a = 0xff00ffaa;
char byte_array[1024]; // this is the array to be transferred over the network
char buff[MAX]="";
sprintf(buff,"%4d",a);
memcpy(byte_array,buff,4);
// fill remaining stuff in the byte array and send it over the network
这里的解码部分:
const int MAX=5;
char buff[MAX]="";
strncat(buff,byte_array,4)
int i=atoi(buff);
// Work with i
这里是我的问题:
1)在上述代码的可移植性?我想这是(请纠正我)
2)现在,我希望编码的字节数组与3个字节(但整数大小为4),即说整数存储0x00ffaabb,我只是希望字节数组有ff int 0th index aa在第一个索引中,bb在第二个索引中。怎么做?
snprinf
似乎没有工作或可能是我失去了一些东西。
已经实施任何网络协议的人可以轻松地帮助我。 解码逻辑仍然会工作我猜。 (strncat(buff,byte_array,3)
后跟atoi
函数调用)。
这里的协议这样说:
--------+--------+--------+--------+------------------------------ |Version| 3 byte length | Remaining stuff --------+--------+--------+--------+------------------------------
版是1个字节,然后是消息的3字节的长度。
我希望能澄清我的问题
谢谢大家的及时帮助。我知道了。我很喜欢从RFC实现一个协议,因此需要所有这些信息。 谢谢tonne :) – ghayalcoder 2009-11-10 09:40:15