代码之家  ›  专栏  ›  技术社区  ›  George G

C++/C:将长度前置到字符[],以字节为单位(二进制/十六进制)

  •  0
  • George G  · 技术社区  · 7 年前

    我希望将UDP数据报从客户端发送到服务器,然后再发送回来。

    char[] )在字节格式中,我很难找到它的示例。我知道如何将其作为实际的文本字符发送,但我想将其作为“有效”的二进制形式发送(例如,如果 length 40 bytes 那么我想预先准备一下 0x28 ,或2字节无符号等效值,而不是ASCII中的“0028” char 形式或类似形式,将是4个字节,而不是潜在的2个字节。

    unsigned int length = dataLength; //length of the data received
    
    char test[512] = { (char)length };
    

    这种方法有效吗?还是会在以后引起问题?

    此外,如果我没弄错的话,这给了我一个255的硬限制。如何最好地将其表示为2个字节以扩展最大长度。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jabberwocky    7 年前

    你可能需要这样的东西:

      char somestring[] = "Hello World!";
      char sendbuffer[1000];
    
      int length = strlen(somestring);
      sendbuffer[0] = length % 0xff;         // put LSB of length
      sendbuffer[1] = (length >> 8) & 0xff;  // put MSB of length
    
      strcpy(&sendbuffer[2], somestring);    // copy the string right after the length
    

    sendbuffer

    LSB 方法 最低有效字节 MSB 方法 最高有效字节 . 这里我们将LSB放在第一位,MSB放在第二位,这个约定称为 小端 ,反之亦然 大端元 . 您需要确保在接收器端正确解码长度。如果接收器端的架构与发送器端不同,则接收器端的长度可能会根据代码解码错误。谷歌“endianness”了解更多详细信息。

    在内存中看起来是这样的:

     0x0c 0x00 0x48 0x65 0x6c 0x6c ...
    |   12    |'H' |'e' |'l' |'l '| ...
    

      //... Decoding (assuming short is a 16 bit type on the receiver side)
    
      // first method (won't work if endiannnes is different on receiver side)
      int decodedlength = *((unsigned short*)sendbuffer);       
    
      // second method (endiannness safe)
      int decodedlength2 = (unsigned char)sendbuffer[0] | (unsigned char)sendbuffer[1] << 8;
    
    
      char decodedstring[1000];
      strcpy(decodedstring, &sendbuffer[2]);
    

    可能的优化:

    如果您发送的大多数字符串的长度小于255,您可以进行优化,不需要系统地预写两个字节,但大多数情况下只能预写一个字节,但这是另一回事。