gpt4 book ai didi

c++ - 在 C++ 中将二进制 Char 数组转换为整数和 double 组

转载 作者:行者123 更新时间:2023-11-30 20:57:04 26 4
gpt4 key购买 nike

我有一个包含二进制格式数字的字符数组。数字采用以下格式:整数、整数和 double 。在 C++ 中将 char 数组转换为整数数组和 double 组的最佳和最快方法是什么?现在我正在使用以下代码,它工作正常,但我认为它不够高效!

#define SIZE    5000
char chBuf[SIZE]; // contains double numbers in binary format
char dBuf[sizeof(double)];
char IBuf[sizeof(int)];
int count =0;
for (int i=0; i<numberofdata; i++)
{
for (int j=0; j<4; j++) IBuf[j] = chBuf[j + count];
Integer[i] = *(integer*) (IBuf);
count += sizeof(integer);

for (int j=0; j<4; j++) IBuf[j] = chBuf[j + count];
Integer[i+1] = *(integer*) (IBuf);
count += sizeof(integer);

for (int j=0; j<8; j++) dBuf[j] = chBuf[j + count];
Double[i] = *(double*) (dBuf);
count += sizeof(double);
}

我认为复制部分到 dBuf[] 和 IBuf[] 应该是不必要的,但我不知道如何摆脱它们。

最佳答案

无需将数据复制到单独的缓冲区。另外,您需要小心不要覆盖您的Integer 值。

int s = 2 * sizeof(int) + sizeof(double);
for (int i = 0; i < numberofdata; i++) {
Integer[2 * i] = *(int*) (chBuf + s * i);
Integer[2 * i + 1] = *(int*) (chBuf + s * i + sizeof(int));
Double[i] = *(double*) (chBuf + s * i + 2 * sizeof(int));
}

关于c++ - 在 C++ 中将二进制 Char 数组转换为整数和 double 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15981115/

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