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

问题描述

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

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

我得到一个 BCD 数字(每个数字都是自己的 4 位表示)

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

例如,我想要什么:

  • 输入:202(十六进制)== 514(十进制)
  • 输出: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 的位表示,然后分成 5 个半字节,然后再次表示为十进制数

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 代码解决问题

I can solve the problem on paper but I just cant get it in a simple C-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:

#include <stdio.h>

int main(void) {

   int binaryInput = 0x202;
   int bcdResult = 0;
   int shift = 0;

   printf("Binary: 0x%x (dec: %d)
", binaryInput , binaryInput );

   while (binaryInput > 0) {
      bcdResult |= (binaryInput % 10) << (shift++ << 2);
      binaryInput /= 10;
   }

   printf("BCD: 0x%x (dec: %d)
", bcdResult , bcdResult );
   return 0;
}

证明:http://ideone.com/R0reQh

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

07-01 09:39