怎么把十六进制转换成十进制? [英] How to convert Hexadecimal to Decimal?
问题描述
我要传入不同的十六进制数据并将其存储到整数类型寄存器中。
I have different hexadecimal data are coming and stored into an integer type register.
当我使用fprint时,我可以看到以下内容:
When I use fprint I can see the following:
0x3076
0x307c
.
.
.
不过,我想显示上述十六进制数据的十进制版本。
However, I would like to show a Decimal version of above-mention Hex data as follows.
12406
12412
.
.
.
从理论上讲,对于第一个值,您可以执行以下操作将其转换为十进制。
In theory, let's say for the first value you do the following to convert it to decimal.
(6* 16^0)+(7 * 16^1)+(0*16^2)+(3*16^3)=6 + 112+ 0 + 12288 = 12406
所以如果我有基于字符的版本 0x3076,并且,如果我能够获得每个字符6-7-0-3,我可以计算小数位数!
So IF I have the character-based version of "0x3076" and also, IF I am able to get each single characters 6 - 7 - 0 - 3, I can calculate the decimal amount!
所以,我决定将 3076除以1000。我应该得到3,但是我得到了两个字符!但是,如果我能在 307c的其余部分中获得3,则不能获得 C。如果是十进制,则可能无法使用十六进制!
So, I decided to divide "3076" by 1000. I was expected to get 3, but I got TWO characters instead! however, if I was able to get 3 for the remainder of "307c" I am not able to get "C". If it was decimal this might work not hex!
此外,我尝试了 strtol
命令。当我使用Cygwin编译代码时,我不确定错误在哪里!我做错了什么?
Also, I tried "strtol
" command. As I use Cygwin to compile my code, I am not sure where the error is! What did I do wrong?
因此,我只需要找到一种方法即可从十六进制数据中获取每个单字符!
So, I just need to find a way to get EACH SINGLE character out of the HEX data!
有什么想法吗?
PS
这是我的代码,可以帮助您
Here is my code in order to help you to give me an idea.
int get_readings(int source, int phase, int max_tries)
{
uint8_t buf[MAX_IEC1107_MSG_BODY];
uint8_t inbuf[MAX_IEC1107_MSG_BODY];
int inlen;
uint8_t *s;
int32_t value;
int status;
double voltage;
double current;
double active_power;
double reactive_power;
double apparent_power;
double power_factor;
double frequency;
s = buf;
*s++ = HOST_CMD_GET_READINGS_PHASE_1 + phase;
*s++ = 0x00;
if (max_tries != 1)
meter_set_max_tries(&emeter[source].meter_msg, max_tries);
if (meter_exchange(&emeter[source].meter_msg, buf, 2, inbuf, &inlen)
&&
inbuf[1] != 0xFF)
{
emeter[source].no_response = FALSE;
s = inbuf;
/* Get current readings */
value = (s[3] << 8) | s[2];
fprint(stderr, "value:" %p\n, value); // this give me HEX code
。
。
。
. . .
推荐答案
只有使用以下行,我才能解决问题!
Only with the following line I could solve the issue!
fprintf(stderr, "Voltage: %.2f\n", value/100.00);
值显示为十六进制,因为我以前使用%p!然后我换成了x!因为我需要124.06而不是12406,换句话说,是2个小数点,所以我加了.2f!
value was shown as HEX as I used to use %p! Then I changed to x! and as I need to have 124.06 not 12406, in other words 2 decimal points, I added .2f!
谢谢大家!
这篇关于怎么把十六进制转换成十进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!