如何在实际二进制位前添加十六进制字节

时间:2013-12-10 05:37:17

标签: c++ winapi binary serial-port hex

我在Win32中发送实际二进制位作为十六进制。代码是

int binText[32]={1,0,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,1,1,1,0,1,0,1,1,1,1,1,0,0,0,1}; //hex:  AF 1A F5 F1
char tempInt[255]={0};
for (int i=0; i<32; i++)
{
    sprintf(&tempInt[strlen(tempInt)], "%d", binText[i]);
}
char HexBuffer[255];
unsigned long int Number = 0;
int BinLength = strlen(tempInt);

for(int i=0; i<32; i++)
{
        Number += (long int)((tempInt[32 - i - 1] - 48) * pow((double)2, i));
}

    //When i send using following code it sends F1 F5 1A AF
    //serialObj.send((char *)&Number);
    //So it is changed into big endian using following code.

unsigned char c1, c2, c3, c4;
c1 = Number & 255;
c2 = (Number >> 8) & 255; //>>right shift operator
c3 = (Number >> 16) & 255;
c4 = (Number >> 24) & 255;
unsigned long int Number1= ((int)c1 << 24) + ((int)c2 << 16) + ((int)c3 << 8) + c4;

//and now following code sends AF 1A F5 F1
serialObj.send((char *)&Number1);

现在我必须在AF 1A F5 F1前面附加三个十六进制字节24 24 3F。我们如何将这些十六进制字节附加到Number1。

“serialObj.send()”调用的“send”函数如下:

void serial::send(char data[])
{
    DWORD dwBytesWrite;
    WriteFile(serialHandle, data, 7, &dwBytesWrite, NULL);
}

1 个答案:

答案 0 :(得分:2)

不是将指向32位变量的指针强制转换为char *,为什么不将这些东西组合成字符呢?

char buf[7] = { 0x24, 0x24, 0x3F };  // first three bytes are prefix

如果你真的需要将一个0和1的32-int数组转换为剩下的四个字节,那么下面的循环将更加简洁:

char buf[7] = { 0x24, 0x24, 0x3F };  // first three bytes are prefix

unsigned char byte = 0;
for (int i = 0; i < 32; i++)
{
    byte = (byte << 1) | binText[i];

    if ( (i & 7) == 7 )
    {
        buf[ 3 + (i >> 3) ] = byte;  // The "3 +" part adds new bytes past the header
        byte = 0;
    }
}
serialObj.send(buf);

但是,如果字符串AF 1A F5 F1实际上是固定的,那么您只需要:

char buf[7] = { 0x24, 0x24, 0x3F, 0xAF, 0x1A, 0xF5, 0xF1 };
serialObj.send(buf);