gpt4 book ai didi

c - 将各种数据类型的值编码为二进制文件(python),然后在c中解码它们

转载 作者:行者123 更新时间:2023-11-30 19:01:43 26 4
gpt4 key购买 nike

我需要将来自各种数据类型的值存储在二进制文件(在 python 中)中,然后在 c 中解码该二进制文件并重建值。为了更清楚地说明,我们假设我们有以下三个变量

a = [1, 2, 3], dtype = int
b = ['sky', 'chair', 'book', 'desk']
c = [3.56, 4.69, 55.0, 1.698], dtype = float32

第1步:将所有数据值导出到二进制文件(数据)

step2:在c中导入二进制文件,然后重建相应的值。

//load binary file ?
...

// declaration
int a[3];
char *b[4];
double c[4];

// decode the binary file to have the same values in c ?
...
a = [1, 2, 3];
b = {'sky', 'chair', 'book', 'desk'};
c = [3.56, 4.69, 55.0, 1.698];

预先感谢您的帮助,

我试图拥有一些可以动态导出二进制文件中的数据并在 C 中动态检索的东西;像这样的数据结构: [整数数量、所有整数值、 float 量、所有浮点值、字符串数量、所有字符串]

例如:[3, 1, 2, 3, 4, 0.2, 0.65, 0.56, 0.33, 2,'天空',' table ']

总之,我还需要在 C 中为解码器传递每种数据类型的元素数量;如果我知道值是按这样的顺序存储的(整数、 float 、字符串)

  • 第 1 步:读取第一个数字 (3),现在我们知道有 3 个 int 值。
  • 第 2 步:将下一个树编号读取为整数。
  • 第 3 步:读取浮点值的数量 (4)。
  • 第4步:读取四个 float 。
  • 第 5 步:读取字符串数量 (2),
  • 第 6 步:读取两个字符串。

我知道我可以使用 struct package 创建二进制包,然后编写它们,但我不知道对于用 C 实现的解包过程应该遵循什么通用策略(!!!)。

最佳答案

a data structure like this: [number of integers, all integers values, number of floats, all float values, number of strings, all strings]

在准备将字符串写入文件时,我会将它们转换为字节,例如。例如:

bb = [s.encode() for s in b]

Python 中的存储部分相当于提供数字和值以及适当的格式字符串。

  • 整数:简单的格式字符串'I%di'%len(a)涵盖整数数量 I所有整数值 %di,其中 %d 替换为 a 中的项目数。
  • float :简单的格式字符串'I%df'%len(c)涵盖 float I所有浮点值 %df,其中 %d 替换为 c 中的项目数。
  • strings:格式字符串不太简单,因为 struct.pack 不允许字符串重复计数,但需要字符串长度。 ''.join(['%ds'%(len(s)+1) for s in bb]) 构造所有字符串值的格式 % ds,其中 %d 替换为每个字符串中的字节数加上终止 NUL 的 1。 (由于没有详细说明,我选择以 C 形式存储字符串。)

这给出:

data = struct.pack('I%di'%len(a)+'I%df'%len(c)+'I'+''.join(['%ds'%(len(s)+1) for s in bb]),
len(a), *a, len(c), *c, len(bb), *bb)
open('data', 'wb').write(data)

C 中的解码部分并不是很复杂,按照您概述的步骤进行,例如:例如:

#include <stdio.h>
#include <stdlib.h>
int geti(FILE *stream)
{ // helper function to read an integer
int i;
if (!fread(&i, sizeof i, 1, stream)) exit(EXIT_FAILURE);
return i;
}

// step 1: Read first number of int values.
int ni = geti(stdin);
int a[ni];
// step 2: Read the next 'ni' numbers as ints.
for (int i = 0; i < ni; ) a[i++] = geti(stdin);
// step 3: Read the number of float values.
int nf = geti(stdin);
double c[nf];
// step 4: read 'nf' float numbers.
for (int i = 0; i < nf; )
{ float f; fread(&f, sizeof f, 1, stdin); c[i++] = f; }
// step 5: read the number of strings,
int ns = geti(stdin);
char *b[ns];
// step 6: read the 'ns' strings.
for (int i = 0, j, c; i < ns; ++i)
{
b[i] = NULL, j = 0;
do
{
b[i] = realloc(b[i], j+1);
c = getc(stdin);
if (c == EOF) exit(EXIT_FAILURE);
} while (b[i][j++] = c);
}

请注意,在此示例中

  1. 当然,您可以使用 stdin 以外的流,
  2. 并非所有错误(读取失败或内存不足)都会得到检查,
  3. 对于源和目的地的号码表示不同的情况没有做出规定;为此,您可以利用 C 中的 struct.pack 字节顺序和大小指示和/或 ntohl()

关于c - 将各种数据类型的值编码为二进制文件(python),然后在c中解码它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57363088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com