[英]Pointer output result
我是C語言的新手,期望輸出為8575
,但輸出為19285
。 任何人都可以幫助解決這里出現的問題嗎?
int main()
{
uint8_t a[4] = {85,75,95,65};
uint16_t *p = a;
uint16_t q = (p[0]);
printf("%u",(unsigned int)(q));
return 0;
}
//新問題
typedef struct{
uint32 a[4];
}x;
/*declare an object of x type*/
x *block2;
uint8 b[64] = {0x01 , 0x02 , 0x03.....0x64}
Api-1
converts b into block* type by
block2 = (x*) b;
這個block2看起來如何?
您的代碼行為未定義(將uint8_t *
處理為uint16_t *
)。
話雖如此,您的代碼還有另外兩個問題,首先,您的計算機似乎是低位字節序,例如,最低有效字節位於最低地址(LSB)中,這是大多數計算機的情況。 其次,您有兩個字節85
和75
並且您希望獲得8575
,將每個字節視為100的冪( 85 * 100 + 75 = 8575
),而字節是256的冪( 85 * 256 + 75 = 21835
)
考慮到這些事實,我們得到的結果數為: 75 * 256 + 85 = 19285
當已知緩沖區的字節序(在這種情況下為大字節序)時,轉換此類數據的安全方法是分別對待每個字節:
uint8_t buff[] = {1, 2, 4, 5};
uint16_t my16;
my16 = buff[0] << 8; // same as * 256
my16 += buff[1];
uint8高達255,因此您認為正確的結果應該是85 * 100 + 75,實際上是75 * 256 + 85 = 19285,因為您的平台也要反轉字節順序。
[想發表評論]
要正確對齊8bit和16bit變量,從而允許將其從8bit指針強制轉換為16bit指針,可以使用並集:
#include <stdint.h>
union Align_to_16bit
{
uint8_t array_u8[4];
uint16_t dummy; /* This takes care of 16bit alignment. */
}
int main(void)
{
union Align_to_16bit aligned_to_16bit =
{
{85, 75, 95, 65};
}
uint16_t * p = (uint16_t*) &aligned_to_16bit; /* dirty, but allowed */
...
請注意,在綠色領域,絕不需要這種(“骯臟”)技巧。 但是,您可能需要它們來避免破壞規范...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.