如何将十六进制数转换为整数? [英] How to convert a hexadecimal number to integer?
问题描述
考虑到我在uint8_t变量中有一个hexa值。现在我该如何将其转换为十进制值?
Consider that I'm having a hexa value in the uint8_t variable. Now how can i convert this to decimal value?
uint8_t one[]={0x00,0x00,0xea,0x60};
int a=*one;
NSLog(@"%d",a);
输出为:0
我试过这样的这样的事情
Output is : 0
I have tried some this like this
uint32_t one={0x0000EA60};
int a=one;
NSLog(@"%d",a);
现在我输出60000.
为什么会这样?
在我的项目中,我喜欢uint8_t变量(这是其他原因的bcz)或者引导我将uint8_t转换为uint32_t变量?
请帮我完成这个通过在第一种情况下获得60000的输出。
提前感谢。
Now i got the output 60000.
Why this happens ?
In my project i'm having like uint8_t variables (this is bcz of other reason) or guide me to convert uint8_t to uint32_t variables?
Please help me to complete this by getting output as 60000 on the first case.
Thanks in advance.
推荐答案
您必须通过添加以创建32位值字节元素移动到正确的位置:
You must create the 32-bit value by adding the byte elements shifted to the correct position:
uint32_t a = (one[3] << 24) | (one[2] << 16) | (one[1] << 8) | one[0];
当然必须是:
It must be of course:
uint32_t a = (one[0] << 24) | (one[1] << 16) | (one[2] << 8) | one[3];
[/ EDIT]
您也可以使用C铸造:
[/EDIT]
You may also use C casting:
uint32_t a = *((uint32_t*)one);
但是演员需要 endianess [ ^ ](字节顺序)与 one
使用的相同array。
But casting requires that the endianess[^] (byte order) of your system is the same as used by your one
array.
int a = *one;
与
is the same as
int a = one[0];
因此结果为零。
hence the zero result.
unsigned char *bytes = {0x00,0x00,0xea,0x60};
NSData *data = [NSData dataWithBytes:bytes length:4];
NSData *timeInt = [data subdataWithRange:NSMakeRange(0,4)];//Ex: 0000ea60
interval = CFSwapInt16BigToHost(*(int*)([timeInt bytes]));
NSLog(@"%d",interval);
输出为:60000: - )
The Output is : 60000 :-)
这篇关于如何将十六进制数转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!