-4

im Converting a uint32_t hex number into uint32_t BCD number. and will do the same to uint64 hex to BCD...

i have this from a uint16

uint16_t CvtBcd(uint16_t HexNumber)
{
  return ((HexNumber/ 10) << 4) | (HexNumber% 10); 
}

edit:

I'm going to use it as an external code to be used for a bigger program.

// Converts a uint32_t hex number into uint32_t BCD number.
extern uint32_t Cvt32Bcd(uint32_t HexNumber)
{
  return ((HexNumber/10) << 8 | (HexNumber % 10));
}
TheHuge_
  • 1,039
  • 17
  • 29
Nazareth
  • 1
  • 1
  • 4
  • 3
    Way to many abbreviations in your question. I'd say just do `uint64_t bla = uint64_t(some_uint32_t);` but I gather you want something else. – rubenvb Jul 30 '12 at 12:15
  • I don't understand what your function is trying to do. I cannot imagine it working because large 16 bit numbers when converted to BCD get wider. They won't even fit on 16 bits. – ArjunShankar Jul 30 '12 at 12:21
  • The OP is referring to [binary-coded decimals](http://en.wikipedia.org/wiki/Binary-coded_decimal), I believe. – Kerrek SB Jul 30 '12 at 12:24
  • 3
    There's no such thing as a "hex integer". An integer doesn't have a base. It's just an integer. Only when you convert it into some particular representation can you speak of "hexadecimal" or other bases. ("0xf3a" is hexadecimal. The integer represented by this string has no base.) – Ambroz Bizjak Jul 30 '12 at 12:47

1 Answers1

2

In a binary coded decimal representation, you need four bits per decimal digit, thus you cannot convert all (unsigned) integers to a BCD representation of the same size, usually you need a larger type for that. Ignoring that problem, an algorithm to convert an unsigned integer of whatever size to its BCD representation is

uintN_t convert_to_BCD(uintN_t n) {
    uintN_t bcd = 0;
    int shift = 0;
    while(n) {
        bcd |= (n % 10) << shift;
        n /= 10;
        shift += 4;
    }
    return bcd;
}

To avoid overflow, make the return type larger than the argument type, but that doesn't work for the largest available input type, of course. You could then use an array of unsigned char to hold the digits, or a struct containing two uintN_ts to hold the result.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431