在表示方面,如何将二进制编码的十进制数字转换为十进制数字?我不想转换它的价值,而是它的表示,这是我的意思。
我希望将0x11转换为十进制11 (不是17),将0x20转换为20 (而不是32)。
unsigned char day = 0x11;
unsigned char month = 0x12;
int dayDecimal, monthDecimal;我希望dayDecimal是11,monthDecimal = 12。我将处理在0x00到0x60之间的范围,所以应该是可能的。没有'A','B','C','D','E','F‘。
更新:
实际上,我正在从RTCC芯片中读取时间,作为我正在进行的嵌入式项目的一部分。以该形式返回小时、分钟、日和月。例如,如果分钟是0x40,那么它意味着40分钟,而不是64分钟,所以我需要能够正确地解释它。我需要将0x40转换成40,而不是64。我希望这是可能的。
谢谢!
发布于 2015-01-25 03:54:58
您需要使用这两个nybbles,将更重要的nybble乘以10,并添加不太重要的:
uint8_t hex = 0x11;
assert(((hex & 0xF0) >> 4) < 10); // More significant nybble is valid
assert((hex & 0x0F) < 10); // Less significant nybble is valid
int dec = ((hex & 0xF0) >> 4) * 10 + (hex & 0x0F);如果断言被禁用,但输入是假的(例如,0xFF),那么您就得到了应得的结果: GIGO --垃圾输入,垃圾输出。您可以轻松地将其包装成(内联)函数:
static inline int bcd_decimal(uint8_t hex)
{
assert(((hex & 0xF0) >> 4) < 10); // More significant nybble is valid
assert((hex & 0x0F) < 10); // Less significant nybble is valid
int dec = ((hex & 0xF0) >> 4) * 10 + (hex & 0x0F);
return dec;
} 这种转换让人联想到BCD - Binary Coded Decimal.
发布于 2017-02-20 09:00:59
一种非常简单的没有错误检查的方法:
int bcd_to_decimal(unsigned char x) {
return x - 6 * (x >> 4);
}发布于 2017-07-14 07:40:42
将所需的值放入函数中,您将得到一个整数作为回报。
#include <stdio.h>
#include <math.h>
typedef int INT32;
typedef short int INT16;
typedef unsigned short int UINT16;
typedef unsigned long int UINT32;
UINT32 BCDToDecimal(UINT32 nDecimalValue){
UINT32 nResult=0;
INT32 nPartialRemainder, ncnt,anHexValueStored[8];
UINT16 unLengthOfHexString = 0,unflag=0;
for(ncnt=7 ;ncnt>=0 ; ncnt--){
anHexValueStored[ncnt]=nDecimalValue & (0x0000000f << 4*(7-ncnt));
anHexValueStored[ncnt]=anHexValueStored[ncnt] >> 4*(7-ncnt);
if(anHexValueStored[ncnt]>9)
unflag=1;
}
if(unflag==1){
return 0;
}
else{
for(ncnt=0 ;ncnt<8 ; ncnt++)
nResult= nResult +anHexValueStored[ncnt]*pow(10,(7-ncnt));
return nResult;
}
}
int main() {
printf("%ld\n",BCDToDecimal(0X20));
return 0;
}https://stackoverflow.com/questions/28133020
复制相似问题