我有一个循环,比如1到32.在这种情况下,1到32是十进制的。我必须在unsigned char数组中插入1到32的十六进制值,然后执行send。我的代码看起来像这样
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'
的错误。
如何在hex unsigned
数组中插入writebuffer
。
何时
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);
}
答案 0 :(得分:1)
您可以合并两行
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将十二进制转换为十六进制,则可以使用:
sprintf(hex, "%02X", dec);
memcpy(writebuffer+3, hex, 2);
如果没有考虑CRC16,你的输出就像"01 05 00 30 31 00 00 00"
一样i = 1.
答案 1 :(得分:0)
您必须使用memcpy复制三个char数组。
答案 2 :(得分:0)
hexunsigned必须是unsigned char数组,而writebuffer [3]是unsigned char。
您不能将unsigned char指定给unsigned char数组。
如果要将hexunsigned复制到writebuffer [3]地址,请使用memcpy。