[英]how to solve this error in c type conversion?
#include <stdio.h>
#include <string.h>
typedef unsigned int uint32;
typedef unsigned char uint8;
int main()
{
double a = 1320.134;
uint32 b;
uint8 c[20];
b = (unsigned int)a;
c[3] = b; //c[3] = (unsigned char)b;
printf("value of %c", c[3]);
return 1;
}
我正在嘗試在程序中進行一些類型轉換。 在主要功能內:1:我正在轉換並將其存儲為雙精度。 2:我想將uint32值存儲在第三個位置的字符數組中,但是如果執行上述操作,則無法獲得輸出。 請有人幫我嗎??
輸出:c <的值。 //一些垃圾值如何在c [3]中讀取1320?
如何閱讀
c[3]
的1320
從數學上講,無法從單個unsigned char
讀取大於255的任何內容。 您看到的值40(0x28,代表一個左括號)是1320的最后八位-截斷0x528的結果。
采用
printf("value of %d", c[3]);
代替
printf("value of %c", c[3]);
此外,8位無符號整數可以高達255。超出部分將被切除。
這是正在發生的事情的概述:
首先,您設置: uint32 b = (unsigned int)(1320.134)
,這使其uint32 b = (unsigned int)(1320.134)
b = 1320
。
1320是一個大於8位的數字,因此它不僅僅適合8位空間( c[3]
),因此它在其中強制它並忽略剩余的位,因此得到1320%256( %表示相除后的余數),恰好是40。現在,將該數字轉換為ascii字符形式后,將其打印出來。
修訂版:
因此,據我了解,您希望下一個元素有一些溢出,因此您需要做一些復雜的指針工作。 這就是我要怎么做。
uint32 b = 1320;
uint8 c[20];
//first, get a pointer to the 3rd array element, and convert it to a uint32 pointer:
uint32 *pointer = &c[3];
//now, lets dereference it and put the value into the location:
*pointer = b;
這應該產生適當的溢出,但是我很好奇,您可能想為此做什么?
它是如何存儲的:
| | | |40|5 | ...
這樣做的原因是1320的二進制表示形式是10100101000。將其反向存儲在內存中,並且最終以如下方式放置這些位:
| | | |00010100|10100000|
當向后讀取時,00010100等於40,而10100000等於5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.