我有这个数组:BYTE set[6] = { 0xA8,0x12,0x84,0x03,0x00,0x00, }
我需要value : "" int Value = 1200; ""
在最后 4 个字节上插入这个.... 实际上是将 int 转换为 hex,然后在数组中写入......这可能吗?
我已经有了BitConverter::GetBytes
功能,但这还不够。
谢谢,
回答原始问题:当然可以。只要你sizeof(int) == 4
和sizeof(BYTE) == 1
.
但我不确定“将 int 转换为 hex”是什么意思。如果你想要一个十六进制字符串表示,你最好只使用一种标准方法来做到这一点。例如,在最后一行我使用 std::hex 将数字打印为十六进制。
这是您一直要求的解决方案以及更多内容(现场示例:http ://codepad.org/rsmzngUL ):
#include <iostream>
using namespace std;
int main() {
const int value = 1200;
unsigned char set[] = { 0xA8,0x12,0x84,0x03,0x00,0x00 };
for (const unsigned char* c = set; c != set + sizeof(set); ++c) {
cout << static_cast<int>(*c) << endl;
}
cout << endl << "Putting value into array:" << endl;
*reinterpret_cast<int*>(&set[2]) = value;
for (const unsigned char* c = set; c != set + sizeof(set); ++c) {
cout << static_cast<int>(*c) << endl;
}
cout << endl << "Printing int's bytes one by one: " << endl;
for (int byteNumber = 0; byteNumber != sizeof(int); ++byteNumber) {
const unsigned char oneByte = reinterpret_cast<const unsigned char*>(&value)[byteNumber];
cout << static_cast<int>(oneByte) << endl;
}
cout << endl << "Printing value as hex: " << hex << value << std::endl;
}
UPD:从评论到您的问题: 1. 如果您只需要在单独的字节中从数字中获取单独的数字,那就另当别论了。2. Little vs Big endianness 也很重要,我在回答中没有考虑到这一点。
你是这个意思吗?
#include <stdio.h>
#include <stdlib.h>
#define BYTE unsigned char
int main ( void )
{
BYTE set[6] = { 0xA8,0x12,0x84,0x03,0x00,0x00, } ;
sprintf ( &set[2] , "%d" , 1200 ) ;
printf ( "\n%c%c%c%c", set[2],set[3],set[4],set[5] ) ;
return 0 ;
}
输出 :
1200