我正在尝试将char数组转换为整数,然后我必须递增该整数(包括小端和大端)。
示例:
char ary[6 ] = { 01,02,03,04,05,06};
long int b=0; // 64 bits
此char将存储在内存中
address 0 1 2 3 4 5
value 01 02 03 04 05 06 (big endian)
Edit : value 01 02 03 04 05 06 (little endian)
-
memcpy(&b, ary, 6); // will do copy in bigendian L->R
这是如何存储在内存中的:
01 02 03 04 05 06 00 00 // big endian increment will at MSByte
01 02 03 04 05 06 00 00 // little endian increment at LSByte
因此,如果我们递增64位整数,则期望值为01 02 03 04 05 07.但是字节顺序是一个很大的问题,因为如果我们直接递增整数的值,它将导致一些错误的数字。对于大端,我们需要在b中移动值,然后对其进行增量。
对于小端,我们可以直接增加。 (编辑:反向和公司)
我们可以将w r t复制到endianess吗?因此,我们不需要担心轮班操作等等。
在将char数组值复制到整数之后递增char数组值的任何其他解决方案?
Linux内核中是否有任何API将w.r.t复制到endianess?
答案 0 :(得分:4)
您需要阅读文档。 This page列出了以下内容:
__u64 le64_to_cpup(const __le64 *);
__le64 cpu_to_le64p(const __u64 *);
__u64 be64_to_cpup(const __be64 *);
__be64 cpu_to_be64p(const __u64 *);
我相信他们足以做你想做的事。将数字转换为CPU格式,递增,然后转换回来。
答案 1 :(得分:4)
除非你希望字节数组表示一个更大的整数,这似乎不是这里的情况,否则endianess无关紧要。 Endianess仅适用于16位或更大的整数值。如果字符数组是8位整数的数组,则endianess不适用。因此,您的所有假设都是不正确的,char数组将始终存储为
address 0 1 2 3 4 5
value 01 02 03 04 05 06
无论结束。
但是,如果您将数组memcpy到uint64_t
,则endianess确实适用。对于大端机器,只需memcpy(),您就可以获得预期格式的所有内容。对于小端,您必须反向复制数组,例如:
#include <stdio.h>
#include <stdint.h>
int main (void)
{
uint8_t array[6] = {1,2,3,4,5,6};
uint64_t x=0;
for(size_t i=0; i<sizeof(uint64_t); i++)
{
const uint8_t bit_shifts = ( sizeof(uint64_t)-1-i ) * 8;
x |= (uint64_t)array[i] << bit_shifts;
}
printf("%.16llX", x);
return 0;
}