Are the functions mentioned in the above predefined somewhere? I’ve seen a few programs referencing them, but never giving the definition. Could anyone point me to some code for them? I’d love to see how they work.

Hello and welcome

Here are the functions:

```
uint8_t decToBcd( int val )
{
return (uint8_t) ((val / 10 * 16) + (val % 10));
}
uint8_t bcdToDec( uint8_t val )
{
return (uint8_t) ((val / 16 * 10) + (val % 16));
}
```

Could you explain a little bit about how they work? They both return a uint8_t[byte], I'm a bit confused about the calculation that just seems to be floating out there. Is that legal? Will those work on non single digit numbers, like say 42. I think I understand the BCD format, I'm just not sure I understand the syntax

Sorry, I have never used these functions, I just found them and pasted them here.

I too don't understand how they work, as I understand the decToBcd should convert for example 9 into 1001, which is greater than a byte...

Maybe someone with more knowledge could reply?

guix:

Sorry, I have never used these functions, I just found them and pasted them here.I too don't understand how they work, as I understand the decToBcd should convert for example 9 into 1001, which is greater than a byte...

A byte is 8 binary digits. 1001 is only four binary digits (a nibble) any you can count from

0 - 15 with a nibble (8 + 4 + 2 + 1 = 15).

The max value of a byte is 255, so 1001 doesn't fit in it... but anyway, I don't understand what these functions do ( I tried to print the result of decToBcd( 9 ) and it printed 9...)

An unsigned 8-bit int is a byte which will hold 256 distinct values, which represent

the values 0 to 255.

If it was a signed 8-bit int, the same 256 possible bit patterns would be taken

to represent the numbers -128 to +127.

In "Binary coded decimal", there are two separate four-bit numbers in each byte.

The decimal digits 0..9 are represented by a four-bit binary number from 0000 to 1001

in the normal binary number scheme ( the same as hexadecimal ), except that the

four remaining bit patterns ( which in hexadecimal represent the digits A to F ( ten to fifteen ) ),

are not used for anything.

In Binary coded decimal arithmetic, you can do decimal arithmetic.

It is not as efficient in space usage as binary schemes, a single byte can only have the

value 00 to 99 so 99 different numbers instead of 256 different numbers.

But it was used in many early computers and for some other uses like pocket calculators

and spacecraft

So if you have unsigned 8-bit numbers and you have the number 00100101 in binary which is 37 then

you convert it to BCD then you will have 00110111 which is 0011 ( 3) and 0111 (7) in two separate half-bytes.

And you can have simple functions which convert one to the other and back again, provided the numbers

are in the acceptable range.