【问题标题】:Read a Fixed Number of (Binary) Bytes from an unsigned const char*从 unsigned const char* 读取固定数量的(二进制)字节
【发布时间】:2014-07-11 20:24:14
【问题描述】:

我在内存中有一个unsigned const char* 缓冲区(来自网络),我需要用它来做一些事情。现在让我难过的是我需要将前两个字节解释为二进制数据,而其余的是 ASCII。我读取 ASCII 没有问题(我认为),但我不知道如何只读取无符号数组的前两个字节,并将它们变成(比如说)一个 int。我打算使用reinterpret_cast,但前两个字节不是以空结尾的,我能找到的唯一其他帮助都是关于文件 IO。

简而言之,我有类似 {0000000000001011}ABC Z123 XY0 5 的东西,其中大括号外的字符被读取为 ASCII,而里面的字符应该是单个二进制数,即 11)。

【问题讨论】:

  • 试试unsigned short int var = ((unsigned short int*)array)[0];

标签: c++


【解决方案1】:
int c1 = buffer[0];
int c2 = buffer[1];
int number = c1 << 8 + c2;

unsigned char* asciiData = buffer+2;

【讨论】:

    【解决方案2】:

    我真的不明白为什么字节必须是“空终止”才能使用 reinterpret_cast。我会做的(并且到目前为止在我的项目中工作)是:

    uint16_t first_bytes = *(reinterpret_cast<const uint16_t*>(buffer));
    

    这将为您获取缓冲区中的前两个字节并将值分配给first_bytes 变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-06
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      相关资源
      最近更新 更多