4
\$\begingroup\$

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.

Example

bcd(0x00000127, 0x00000003, '+') => 0x00000130 // NOT 0x0000012A
\$\endgroup\$
1
\$\begingroup\$

Python - 47 chars

bcd=lambda*a:"0x%08d"%eval("%x%s%x"%(a*2)[::2])

tests

>>> print bcd(0x00000127, 0x00000003, '+')
0x00000130
>>> print bcd(0x00000127, 0x00000003, '*')
0x00000381
>>> print bcd(0x00000127, 0x00000003, '/')
0x00000042
>>> print bcd(0x00000127, 0x00000003, '-')
0x00000124
\$\endgroup\$
  • \$\begingroup\$ I guess the question says we have to return as a BCD? codepad.org/6SyEB7DJ \$\endgroup\$ – Dogbert Feb 11 '11 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 '11 at 12:03
1
\$\begingroup\$

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.

Test:

> f 0x127 0x3 +
0x130

History:

  • 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.
\$\endgroup\$
0
\$\begingroup\$

JavaScript ES6, 61 bytes

(a,b,y)=>0|'0x'+~~eval([a,b].map(t=>+t.toString(16)).join(y))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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