在字节数组中嵌入多个int [英] Embed multiple ints in byte array
问题描述
我使用这个代码:
int number; //=smth
unsigned char sendBuffer[255];
sendBuffer[0] = number & 0xFF;
sendBuffer[1] = (number >> 8) & 0xFF;
sendBuffer[2] = (number >> 16) & 0xFF;
sendBuffer[3] = (number >> 24) & 0xFF;
将数字
c $ c> sendBuffer 。
to put number
in byte array sendBuffer
.
我的问题是:
我想现在嵌入两个数字在字节数组,我应该这样继续?
1) Say I want to embed now two numbers in the byte array, shall I proceed like this?
sendBuffer[0] = number & 0xFF;
sendBuffer[1] = (number >> 8) & 0xFF;
sendBuffer[2] = (number >> 16) & 0xFF;
sendBuffer[3] = (number >> 24) & 0xFF;
sendBuffer[4] = number2 & 0xFF;
sendBuffer[5] = (number2 >> 8) & 0xFF;
sendBuffer[6] = (number2 >> 16) & 0xFF;
sendBuffer[7] = (number2 >> 24) & 0xFF;
即使 code> 大小为8或6个字节?
(我这么说是因为在某些平台上int可能是4个字节或6个是正确的
想想如果上面的代码也工作,当数字是6字节吗?
另外要注意的是,即使它是6字节,但我只有
存储4字节整数内部,将上面的代码工作吗? 。
Will this work even if number
is of size say 8 or 6 bytes?
(I am saying this because on some platforms the int maybe 4 bytes or 6 right?
So I was thinking if the above code also works when number is 6 bytes?
Further thing to note is that even if it is 6 bytes, but I only
store 4 byte integer inside it, will above code work?).
这个缓冲区通常存储在卡的某些内存上,我没有读取
的问题(例如,endiannes等问题,字节数组,当读取看来是按照我保存的顺序)。
This buffer I usually store on some memory of a card and I don't have problems reading it back (e.g., endiannes etc. issues, the byte array when reading seems to come in the order I saved).
2)最后,如何从字节数组重建整数 sendBuffer
?
2) Finally, how to reconstruct the integer from the byte array sendBuffer
?
推荐答案
1)是的,不,它只有4个字节。
1) Yes, proceed like that. No, it only works for 4 bytes.
有一个更简单,更好的方法来做到这一点,虽然如果缓冲区从一台计算机发送,它可能会导致字节顺序问题另一个使用不同的架构。假设你知道 number
的类型,在 sendBuffer
之上覆盖另一个数组。
There is a easier, better way to do this, although it can cause endianness issues if the buffer is sent from one computer to another which uses a different architecture. Assuming you know the type of number
, overlay another array on top of sendBuffer
.
unsigned char sendBuffer[255];
number_type *sendBufferNum = (number_type*) sendBuffer;
sendBufferNum[0] = number;
sendBufferNum[1] = number2;
以同样的方式读取数字。
Reading a number can be done the same way.
unsigned char receiveBuffer[255];
//read values into receiveBuffer
number_type *receiverBufferNum = (number_type*) receiveBuffer;
number_type number = recieveBuffer[0];
number_type number2 = receiveBuffer[1];
这篇关于在字节数组中嵌入多个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!