我有这个数组:BYTE set[6] = { 0xA8,0x12,0x84,0x03,0x00,0x00, }
,我需要在最后4个字节中插入这个value : "" int Value = 1200; ""
....实际上是从int转换为hex,然后写入数组... 这可能吗?将int值写入字节数组中
我已经有BitConverter::GetBytes
函数,但这还不够。
谢谢
我有这个数组:BYTE set[6] = { 0xA8,0x12,0x84,0x03,0x00,0x00, }
,我需要在最后4个字节中插入这个value : "" int Value = 1200; ""
....实际上是从int转换为hex,然后写入数组... 这可能吗?将int值写入字节数组中
我已经有BitConverter::GetBytes
函数,但这还不够。
谢谢
要回答原来quesion:当然可以。 只要你的sizeof(int) == 4
和sizeof(BYTE) == 1
。
但我不确定你的意思是“将int转换为十六进制”。如果你想要一个十六进制字符串表示,只需使用其中一种标准方法即可。 例如,在最后一行,我使用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.小vs大排序也很重要,我没有在我的答案中说明这一点。
这是在数组内写入新值的简单方法: BYTE byt [16] = {0xC7,0x80,0xEA,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x8,0xE5,0x5D, 0xC2,0x08,0x00}; \t \t int value = 300; \t \t int tmp = value; 对(INT I = 6; I <10; ++ⅰ) \t \t { \t \t \t myArray的[I] =(TMP&为0xFF); \t \t \t tmp = tmp >> 8; \t \t} 这将用数组中的int值,第6,第7,第8,第9个字节重写。 真棒:D ...我现在无法回答我自己的问题...如果有人愿意以正确的格式发布答案....谢谢, – user2558921
您的意思是?
#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 ;
}
输出:
有错误....来源。cpp(18):错误C2664:'sprintf':无法将参数1从'unsigned char *'转换为'char *'。我已经解决了这个问题。谢谢, – user2558921
是你想要的memcpy? – ondrejdee
你打算将'set'从6个字节增长到10个,还是只更换最后4个字节? –
你还没有提到你是希望它存储在大的还是小的endian中,它*会*有所作为 – WhozCraig