使用 uint8_t byte[]
数组的替代方案是使用结构体,利用每个 addr
和 id
的 bitfield
。你可能会发现它更方便,但它确实提供了一种简单的方法来保持与任何给定的 addr/id
对关联的偏移信息。
我不相信有一种直接利用结构体类型指定初始化器来填充uint8_t byte
数组的方法。我认为最接近完整初始化的方法是使用memcpy
。我在下面的示例中包含了它。请注意,没有任何东西阻止您使用memcpy
填充uint8_t byte
数组,但是您必须跟踪uint8_t byte
数组中的offset
,以准确地指向addr
或id
中的任何给定字节。这就是位域使事情变得稍微容易的地方。您可以在a1..4
和b1..4
中找到每个addr
和id
中的字节。
下面是一个使用uint8_t
数组的版本。
这里是一个简短的示例,其中包含一个struct Device
数组中的测试数据:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
typedef struct /* bitfield corresponding to struct Device */
{
unsigned int a1 : 8,
a2 : 8,
a3 : 8,
a4 : 8;
unsigned int b1 : 8,
b2 : 8,
b3 : 8,
b4 : 8;
} uibitfield;
struct Device {
uint32_t addr;
uint32_t id;
};
int main () {
struct Device dev[] = { {0x4009f0, 0}, {0x4009f1, 1}, {0x4009f2, 2}, {0x4009f3, 3},
{0x4009f4, 4}, {0x4009f5, 5}, {0x4009f6, 6}, {0x4009f7, 7},
{0x4009f8, 8}, {0x4009f9, 9}, {0x4009fa, 10}, {0x4009fb, 11},
{0x4009fc, 12}, {0x4009fd, 13}, {0x4009fe, 14}, {0x4009ff, 15},
{0x400a00, 16}, {0x400a01, 17}, {0x400a02, 18}, {0x400a03, 19} };
int it = 0;
size_t sz = sizeof (dev)/sizeof (*dev);
uibitfield *bytes = calloc (sz, sizeof (*bytes));
if (!bytes) {
fprintf (stderr, "error: allocation failed.\n");
return 1;
}
memcpy (bytes, dev, sz * sizeof (dev));
for (it = 0; it < sz; it++)
printf ("\n addr[%2d]: 0x%02x, 0x%02x, 0x%02x, 0x%02x\n id[%2d]: 0x%02x, 0x%02x, 0x%02x, 0x%02x\n",
it, (bytes + it)->a1, (bytes + it)->a2, (bytes + it)->a3, (bytes + it)->a4,
it, (bytes + it)->b1, (bytes + it)->b2, (bytes + it)->b3, (bytes + it)->b4);
printf ("\n");
return 0;
}
输出:
$ ./bin/memview
addr[ 0]: 0xf0, 0x09, 0x40, 0x00
id[ 0]: 0x00, 0x00, 0x00, 0x00
addr[ 1]: 0xf1, 0x09, 0x40, 0x00
id[ 1]: 0x01, 0x00, 0x00, 0x00
addr[ 2]: 0xf2, 0x09, 0x40, 0x00
id[ 2]: 0x02, 0x00, 0x00, 0x00
addr[ 3]: 0xf3, 0x09, 0x40, 0x00
id[ 3]: 0x03, 0x00, 0x00, 0x00
addr[ 4]: 0xf4, 0x09, 0x40, 0x00
id[ 4]: 0x04, 0x00, 0x00, 0x00
(snip)
注意:不清楚您将如何使用/填充“struct Device”以及您希望在“stuct Device”中查看多少初始数据,因此这只是一个查看数据的示例。
使用uint8_t字节数组:
如果您确实想要使用`uint8_t`数组,则需要进行的更改很少:
/* using a uint8_t byte array */
uint8_t *bytearr = calloc (sz * 4, sizeof (*bytearr))
if (!bytearr) {
fprintf (stderr, "error: allocation failed.\n")
return 1
}
memcpy (bytearr, dev, sz * sizeof (dev))
/* print bytes in each addr & id in dev using uint8_t array */
for (it = 0
printf ("\n addr[%2d]: 0x%02x, 0x%02x, 0x%02x, 0x%02x\n id[%2d]: 0x%02x, 0x%02x, 0x%02x, 0x%02x\n",
it, bytearr[it], bytearr[it+1], bytearr[it+2], bytearr[it+3],
it, bytearr[it+4], bytearr[it+5], bytearr[it+6], bytearr[it+7])
输出相同
uint8_t
持有值为456
的数。 - Sourav Ghosh