c++ - 如何在十六进制字符数组中插入十六进制值

标签 c++ winapi binary hex

我有一个从 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 010x02 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/

相关文章:

C++ 一种返回十进制值作为二进制整数的方法,用 bool 数组表示

c++ - 如何正确组合来自基类和派生类的函数以避免警告?

java - Java字节设置操作中字节的符号(+/-)错误

windows - 如果从静态库调用,Atl CDialogImpl 不会显示在 DoModal 上

c# - 将所有低位设置为 0,直到剩下两个 1(对于存储为字节数组的数字)

c - 如果我在这个将十进制转换为二进制的 C 程序中输入大于 16383 的值,则它不起作用。为什么?

c++ - __PRETTY_FUNCTION__、__FUNCTION__、__func__ 有什么区别?

c++ - 汇编代码与我的 C++ 代码混合在一起。如何移植到 64 位

c - 在C编程中使用窗口类型图形

c - 无法将多行文本文件复制到缓冲区