Write the shortest function you can that takes two binary-coded decimal integers and a character indicating an arithmetic operation to perform and return the result.

Input Specification
You will be passed two 32-bit bit patterns representing unsigned BCD integers. In C or Java, for example, you would be passed an int (unsigned, if you prefer). The third argument to your function will be a single character denoting what operation to perform. If your language requires fixed return sizes, return a 32-bit result and ignore overflow. Your return value should also be encoded as a BCD.

You should support +, -, *, /, and %. For subtraction, the first argument is the minuend and the second argument is the subtrahend. For division and modulo, the first argument is the quotient and the second is the divisor.


bcd(0x00000127, 0x00000003, '+') => 0x00000130 // NOT 0x0000012A

3 Answers 3


Python - 47 chars



>>> print bcd(0x00000127, 0x00000003, '+')
>>> print bcd(0x00000127, 0x00000003, '*')
>>> print bcd(0x00000127, 0x00000003, '/')
>>> print bcd(0x00000127, 0x00000003, '-')
  • \$\begingroup\$ I guess the question says we have to return as a BCD? codepad.org/6SyEB7DJ \$\endgroup\$
    – Dogbert
    Feb 11, 2011 at 9:16
  • \$\begingroup\$ @Dogbert, perhaps, but it doesn't really make sense to me to talk about passing in / returning a BCD. BCD here is just painting "0x" in front of the decimal representation of the number, which is quite different from using BCD numbers in assembler \$\endgroup\$
    – gnibbler
    Feb 11, 2011 at 12:03

Windows PowerShell, 54 56 69

filter f($a,$b,$o){'0x'+("{0:x}$o{1:x}"-f+$a,+$b|iex)}

A bit cheating, I guess, but the output very well works as input again. I.e., PowerShell doesn't care whether it's a string or actual numeric literal there.


> f 0x127 0x3 +


  • 2011-02-11 10:35 (69) – First attempt.
  • 2011-02-11 10:36 (56) – Going easy on the extra zeroes.
  • 2011-02-11 10:41 (54) – filter is shorter.

JavaScript ES6, 61 bytes


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.