从C中的字节数组一次读取两个字节

问题描述 投票:2回答:2

假设我有以下字节数组:

uint8_t barr[4] = {0xCE, 0xCE, 0xCE, 0xCE};

给定索引n,我希望能够读取两个字节:

uint16_t d16 = barr[0];

并且d16等于

0xCECE

也许标准库中有一个可以执行此类任务的功能?

c arrays memory
2个回答
8
投票

一块蛋糕:

memcpy(&d16, barr + n, sizeof(d16));

不要尝试转换指针或使用unions。这些都是未定义的行为,或者可能会使陷阱表示失效。 memcpy()是“规范”解决方案(正如C ++ boost库所做的那样)。


0
投票

这里采用线性和字节顺序安全的方法:

#include <stdint.h>
#include <stdio.h>
#include <arpa/inet.h> /* for ntohs() */

union Convert
{
  uint16_t  to_integer_big_endian;
  uint8_t barr[sizeof (uint16_t)];
};

uint16_t pick_and_convert(uint8_t * barr, size_t s, size_t n)
{
  union Convert c = {0};  /* Take out-of-bound bytes as 0s. */

  for (size_t i = 0; i < sizeof c.barr && (n + i) < s; ++i)
  {
    c.barr[i] = barr[n + i];
  }

  return ntohs(c.to_integer_big_endian);
}

int main(void)
{
   uint8_t barr[4] = {1, 2, 3, 4}; /* Assuming a binary sequence. */
   size_t n;

   scanf("%zu", &n);

   uint16_t to_integer = pick_and_convert(barr, sizeof barr / sizeof *barr, n);

   printf("result = 0x%hx\n", to_integer);
 }
© www.soinside.com 2019 - 2024. All rights reserved.