我真的很困惑。
uint8_t hash[20];
uint32_t u;
// Setting hash to some value here...
u = *(uint32_t*) hash;
此*(uint32_t*) 哈希
导致警告:
取消引用类型双关指针将打破严格的别名规则 [-Wstrict-aliasing]
。
我认为类型转换有问题,但我不确定,因为我不清楚 *(type*) var
类型转换的实际工作方式。它似乎也指向一个内部带有星号的对象。我很困惑,这就是迫使我问这个问题的原因。
我特别想知道 type*
与 *(type*)
有何不同。这可能对摆脱这个警告有很大帮助。
提前致谢。
你不能像你这样通过不兼容的指针来解释对象:
*(uint32_t*) hash;
这样做会导致对齐、字节序和违反严格别名的问题,这将导致未定义的行为。
实际情况是,您将数组哈希的前四个字节解释为无符号 32 位整数。
uint32_t* p = ( uint32_t* )hash ; //cast must be there, pointer p is not valid
uint32_t u = *p ; //dereference the pointer, this is undefined behaviour
如果您的字节数组正在编码 little endian 32 位无符号整数,这是可移植的、独立于字节顺序的提取方式:
#include <stdint.h>
#include <limits.h>
uint8_t h[] = { 3 , 2 , 1 , 0 } ; //1*3 + 256*2 + 65536*1 + 16777216 * 0
uint32_t a = 0 ;
for( size_t i = 0 ; i < sizeof( a ) ; i++ )
{
a = a | ( h[i] << ( CHAR_BIT*i ) ) ;
}
printf("%u" , a ) ; //66051