如何在标准C ++中进行C#BitConverter.GetBytes()操作。
例如;
int k=4;
byte[] byteK = BitConverter.GetBytes(K);
- byte [0] = 0 0 0 0 0 1 0 0
- byte [1] = 0 0 0 0 0 0 0 0
- byte [2] = 0 0 0 0 0 0 0 0
- byte [3] = 0 0 0 0 0 0 0 0
答案 0 :(得分:1)
假设整数类型变量占用4个字节,
int k = 4;
unsigned char byteK[4];
byteK[0] = (unsigned char)k & 0xFF;
byteK[1] = (unsigned char)((k >> 8) & 0xFF);
byteK[2] = (unsigned char)((k >> 16) & 0xFF);
byteK[3] = (unsigned char)((k >> 24) & 0xFF);
可以使用循环来执行相同操作,以将操作概括为不同大小的数据类型。
for (int i = 0; i < noOfBytes; i++)
{
byteK[i] = (unsigned char)(( k >> (8 * i)) & 0xFF);
}
顺序取决于系统的字节顺序,可以使用简单的按位测试来确定。 int x = 1; char ptr =(char )&amp; x; if(* ptr == 1) {// Little Endian }