【问题标题】:how I can set binary data in a char[]如何在 char[] 中设置二进制数据
【发布时间】:2012-05-15 07:20:11
【问题描述】:

我有我需要插入缓冲的 const 二进制数据 例如

 char buf[] = "1232\0x1";

但是当二进制数据最初如下所示时怎么办

 char buf[] = "\0x11232";

编译器把它看成一个很大的十六进制数 但我的目的是

 char buf[] = {0x1,'1','2','3','2'};

【问题讨论】:

  • \0x1 不是十六进制的 1,而是一个 NULL 字节,后跟字符“x”和“1”
  • 您不能使用前两个 sn-ps 中的任何一个。就像你的第三个 sn-p 那样做长手。

标签: c++ c


【解决方案1】:

您可以使用编译时字符串连接:

char buf[] = "\x01" "1232";

不过,\x 后面有 2 位数字也可以:

char buf[] = "\x011232";

【讨论】:

【解决方案2】:

您可以通过将相邻字符串组合在一起来创建单个字符串文字 - 编译器会将它们连接起来:

char buf[] = "\x1" "1232";

相当于:

char buf[] = {0x1,'1','2','3','2', 0};  // note the terminating null, which may or may not be important to you

【讨论】:

    【解决方案3】:

    你必须写成两字节或四字节格式:

    \xhh = ASCII character in hexadecimal notation
    
    \xhhhh = Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode string literal.
    

    所以在你的情况下你必须写"\x0112345"

    【讨论】:

      猜你喜欢
      • 2013-10-19
      • 2013-11-09
      • 1970-01-01
      • 2010-11-09
      • 2015-11-05
      • 2017-08-16
      • 2015-09-12
      • 2011-12-31
      • 1970-01-01
      相关资源
      最近更新 更多