本文介绍了从(折纯)二进制整数转换到BCD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到现在愚蠢来解决这个问题...

I'm to stupid right now to solve this problem...

我得到一个BCD数字(每个数字是一个自己4Bit的再presentation)

I get a BCD number (every digit is an own 4Bit representation)

例如,我想要什么:


  • 输入:202(十六进制)== 514(DEC)

  • 输出:BCD 0x415

  • Input: 202 (hex) == 514 (dec)
  • Output: BCD 0x415

输入:0x202

有什么我试过:

unsigned int uiValue = 0x202;
unsigned int uiResult = 0;
unsigned int uiMultiplier = 1;
unsigned int uiDigit = 0;


// get the dec bcd value
while ( uiValue > 0 )
{
    uiDigit= uiValue & 0x0F;
    uiValue >>= 4;
    uiResult += uiMultiplier * uiDigit;
    uiMultiplier *= 10;
}

但我知道这是非常错误的,这将是202重新presentation位,然后分成5个半字节,然后再psented为十进制数$ P $再次

But I know that's very wrong this would be 202 in Bit representation and then split into 5 nibbles and then represented as decimal number again

我可以解决在纸面上的问题,但我只是不能得到它在一个简单的C code

I can solve the problem on paper but I just cant get it in a simple C-Code

推荐答案

您得到了它南辕北辙。您code从 BCD转换为二进制,就像你的问题的(原)标题说。但是,你所提供的输入和输出值仅当您从二进制转换为BCD 正确的。在这种情况下,尝试:

You got it the wrong way round. Your code is converting from BCD to binary, just as your question's (original) title says. But the input and output values you provided are correct only if you convert from binary to BCD. In that case, try:

while (uiValue > 0) {
   uiResult <<= 4;
   uiResult |= uiValue % 10;
   uiValue /= 10;
}

证明:

这篇关于从(折纯)二进制整数转换到BCD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 21:10