gpt4 book ai didi

c - 对指针进行类型转换以更改其大小(以字节为单位)

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:21 25 4
gpt4 key购买 nike

我正在尝试使用指针在充满十六进制值的内存区域中移动。我使用 uint8_t 指针来确保它一次只指向 1 个字节。我想转到一个特定位置(从起始位置偏移字节数)并存储一组长度为 1、2、4 或 8 字节的字节。然后我想将该值解释并打印为有符号或无符号十进制(由枚举参数确定)。

我认为我可以简单地将指针从 1 字节 uint8_t 更改为字节数的正确大小(例如 uint64_t 为 8 btyes)然后存储该值(因为我不能只打印它一次一个字节,我需要评估整个字节/字节组)。这是我目前所拥有的:

void showValueAtOffset(FILE* Out, const uint8_t* const baseAddr, uint32_t Offset, Sign Sgn, uint8_t nBytes) {//------------------doesn't work----------------
uint8_t *p = baseAddr;//create a pointer that points to the first byte of memory in the array
for(int i = 0; i < Offset; i++){//use a for loop to move p to the location indicated by Offset
p++;
}
if(nBytes == 1){
//pointer p already has the correct typecast for the number of bytes
uint8_t N = *p;//store the value of the byte
if(Sgn == SIGNED){
int8_t result = N;
fprintf(Out, "%d ", result);//print the value
}
else{//if UNSIGNED
fprintf(Out, "%u ", N);//print the value
}
}
else if(nBytes == 2){
uint16_t q = (uint16_t) p;//create the pointer q with the correct typecast for the number of bytes
uint16_t N = *q;//store the value of the bytes
if(Sgn == SIGNED){
int16_t result = N;
fprintf(Out, "%d ", result);//print the value
}
else{//if UNSIGNED
fprintf(Out, "%u ", N);//print the value
}
}
else if(nBytes == 4){
uint32_t q = (uint32_t) p;//create the pointer q with the correct typecast for the number of bytes
uint32_t N = *q;//store the value of the bytes
if(Sgn == SIGNED){
int32_t result = N;
fprintf(Out, "%d ", result);//print the value
}
else{//if UNSIGNED
fprintf(Out, "%u ", N);//print the value
}
}
else if(nBytes == 8){
uint64_t q = (uint64_t) p;//create the pointer q with the correct typecast for the number of bytes
uint64_t N = *q;//store the value of the bytes
if(Sgn == SIGNED){
signed int result = (signed int) N;
fprintf(Out, "%d ", result);//print the value
}
else{//if UNSIGNED
unsigned int result = (unsigned int) N;
fprintf(Out, "%u ", result);//print the value
}
}
else{
//this should not happen according to the preconditions
}
fprintf(Out, "\n");
}

这行不通,我收到了几个错误,例如“无效的类型争论‘unary *’(有‘uint32_t’)”和“警告:从指针转换为不同大小的整数”。

我做错了什么?

最佳答案

错误的直接来源是您应该使用uint16_t *q = (uint16_t *) p;,而不是uint16_t q = (uint16_t) p;,即将一个指针类型强制转换为另一个指针类型,然后再解析它。

仍然,修改后的代码依赖于机器架构,存在大/小端和对齐的问题。简而言之,该代码将在 x86 机器上运行,但可能会由于未对齐的内存访问而崩溃,或者在其他体系结构上产生错误的数字。一种可移植的方式是这样的:

uint32_t to_uint32_be(const void* num)
{
const uint8_t *p = num;
uint32_t res = 0U;
int i;
for (i = 0; i < 4; i++)
res = (res << 8) + p[i];
return res;
}

在上面的代码中,'be'代表big-endian,即数据以网络字节顺序存储,最高有效字节在前。

关于c - 对指针进行类型转换以更改其大小(以字节为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29441088/

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