C++ 如何在十六进制字符数组中插入十六进制值
我有一个从1到32的循环。在这种情况下,1到32是十进制的。我必须在无符号字符数组中插入1到32的十六进制值,然后执行send。我的代码如下所示C++ 如何在十六进制字符数组中插入十六进制值,c++,winapi,binary,hex,C++,Winapi,Binary,Hex,我有一个从1到32的循环。在这种情况下,1到32是十进制的。我必须在无符号字符数组中插入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
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);
将错误显示为无法从'unsigned char[3]
转换为'unsigned char'
如何在
writebuffer
数组中插入hex无符号
什么时候
使用时,它将01(十二月)转换为31
我也试过下面的代码,它也把01(12月)翻译成31
我认为它将在十六进制变量处接收的“1”视为ascii,并将字符“1”的十六进制值发送为31
发送功能如下所示:
void serial::send(unsigned char data[], DWORD noOfByte)
{
DWORD dwBytesWrite;
WriteFile(serialHandle, data, noOfByte, &dwBytesWrite, NULL);
}
您必须使用memcpy来复制一个三字符数组。您可以合并这两行
memcpy(hexunsigned,hex,sizeof(hexunsigned)); //converting char to unsigned char
writebuffer[3]= hexunsigned;
合二为一:
memcpy(writebuffer+3, hex, 3);</strike>
对于不考虑CRC16的i=1,您的输出将如下所示。hexunsigned必须是无符号字符数组,writebuffer[3]是无符号字符 不能将无符号字符分配给无符号字符数组
如果要将hexunsigned复制到writebuffer[3]地址,请使用memcpy。hexunsigned是什么类型的?使用上面的memcpy,它将发送i=1的“01 05 00 31 00 cc 9c 50”;它正在将1转换为31。其他i=2转换为32。对于i=1,它应该是01而不是31。如何正确转换i=1的“01 05 00 01 00 cc 9c 50”预期输出?i=12的预期产量是多少?是的,i=12的预期产量是“01 05 00 01 00 cc 9c 50”,我的预期产量是01 02 00 0C 00 cc 9c 50。我的代码将12视为字符并发送其十六进制值……(如果是这样,它肯定不是十六进制,您可以简单地使用
writebuffer[3]=dec
decimal值01将被转换为31而不是01。原因是什么sprintf(hex,“%X”,1)
将分配十六进制='1'(注意,它是字符'1'而不是数字1)之后,如果使用printf(“%X”,十六进制[0])
您将看到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>
sprintf(hex, "%02X", dec);
memcpy(writebuffer+3, hex, 2);