我有一个从 1 到 32 的循环。在这种情况下,1 到 32 是十进制。我必须将 1 到 32 的十六进制值插入到一个无符号字符数组中,然后执行发送。我的代码看起来像这样
char hex[3];
unsigned char hexunsigned[3];
int dec;
int i=0;
do
{
// this is the unsigned char array , i have to insert at 4th pos.
unsigned char writebuffer[8] ={0x01, 0x05, 0x00, 0x20, 0xFF, 0x00, 0x00, 0x00};
// to place the hex value of each point on writeBuffer[3]
dec=i+1;
decimal_hex(dec,hex); //this function returns hex value of corresponding i value.
memcpy(hexunsigned,hex,sizeof(hexunsigned)); //converting char to unsigned char
writebuffer[3]= hexunsigned; //shows the error cannot convert from 'unsigned char [3]' to 'unsigned char'
unsigned short int crc = CRC16(writebuffer, 6); // Calculates the CRC16 of all 8 bytes
writebuffer[6] = ((unsigned char*) &crc)[1];
writebuffer[7] = ((unsigned char*) &crc)[0];
serialObj.send(writebuffer, 8);
//send another packet only after getting the response
DWORD nBytesRead = serialObj.Read(inBuffer, sizeof(inBuffer));
i++;
}while(nBytesRead!=0 && i<32);
所以,这条线
writebuffer[3]= hexunsigned;
显示无法从 'unsigned char [3]'
转换为 'unsigned char'
的错误。
如何在 writebuffer
数组中插入 hex unsigned
。
当
char hex[3];
int dec;
dec=i+1;
decimal_hex(dec,hex);
memcpy(writebuffer+3, hex, sizeof(writebuffer+3));
被使用,它将 01(dec) 翻译成 31。
我也试过下面的代码,它也将 01(dec) 翻译成 31。
sprintf(hex, "%X", dec);
memcpy(writebuffer+3, hex, sizeof(writebuffer+3));
我认为它将在十六进制变量中接收到的“1”视为 ascii,并将字符“1”的十六进制值作为 31 发送。
发送函数如下:
void serial::send(unsigned char data[], DWORD noOfByte)
{
DWORD dwBytesWrite;
WriteFile(serialHandle, data, noOfByte, &dwBytesWrite, NULL);
}
最佳答案
你可以合并这两行
memcpy(hexunsigned,hex,sizeof(hexunsigned)); //converting char to unsigned char
writebuffer[3]= hexunsigned;
合二为一:
memcpy(writebuffer+3, hex, 3);</strike>
临时的hexunsigned是多余的
--------------------更新行--------------------
其实我们说十六进制编码的时候,我们想用两个字节来表示一个原始字节,比如
0x33 30//'3' '0'
代表 0x30
所以在你的情况下,0x01~0x20
应该表示为 0x00 01
到 0x02 00
,如果你想使用 sprintf 从 dec 转换为 hex ,你可以这样使用:
sprintf(hex, "%02X", dec);
memcpy(writebuffer+3, hex, 2);
对于 i=1,不考虑 CRC16,您的输出将像这样 "01 05 00 30 31 00 00 00"
。
关于c++ - 如何在十六进制字符数组中插入十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20625997/