如何将 BCD 数乘(或除)10^x
我有一个大的(12 位)BCD 数字,编码在 6 个字节的数组中 - 每个半字节都是一个 BCD 数字。 我需要将它乘以 10^x,其中 x 可以是正数或负数。
我知道可以通过向左或向右移动半字节而不是位来完成,但这是一个可怕的实现 - 特别是在我正在使用的 Javacard 中。 有没有更好的办法?
I have a large (12 digit) BCD number, encoded in an array of 6 bytes - each nibble is one BCD digit. I need to multiply it by 10^x, where x can be positive or negative.
I know it can be done by shifting left or right by nibble instead of bit, but it's a horrible implementation - especially in Javacard, which is what I'm using. Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过半字节移位是最有效的方法。
如果性能不是您的问题并且您想要拥有最具可读性的版本,您可能需要将 BCD 数字转换为字符串并移动小数点。
如果您没有小数点(例如您的数字是整数),则如果 x > 则可以连接零。 0 或删除最后一个 -x 字符(如果 x <) 0.
然后将字符串转换回 BCD。 请注意溢出以及删除所有字符并最终得到空字符串的情况。
Shifting by nibbles is the most efficient way.
If performance is not your problem and you want to have the most readable version you may want to convert your BCD-number to a string and move the decimal point around.
In case you don't have a decimal point (e.g. your number is an integer) you can concat zeros if x > 0 or delete the last -x characters if x < 0.
Afterwards convert the string back to BCD. Watch out for overflows and and cases where you delete all characters and end up with an empty string.
您不必使用位移位(尽管这可能是最有效的方法)。
对于您的 12 位 BCD 数字,假设不会发生任何溢出,假设 b[5] 到 b[0] 保存从最高有效位到最低有效位的字节,并且 mod 是模(余数)运算,div是整数除法,下面的伪代码将乘以 10:
老实说,这可能比位移解决方案更难看,但是只要您将它们中的任何一个封装在函数中,它就应该不重要。
我建议有一个类似以下的函数:
它将通过应用 10 的幂返回修改后的数组。
任何 10 的偶次幂都是字节的简单副本(因为两个半字节是一个字节),而只有 10 的奇次幂需要棘手的位移位或余数/除法代码。
You don't have to use bit-shifting (although that is probably the most efficient way of doing it).
For your 12-digit BCD number, provided there won't be any overflow, assume that b[5] through b[0] holds your bytes from most significant to least significant, and that mod is the modulus (remainder) operation and div is integer division, the following pseudo-code would multiply by 10:
To be honest, that's probably uglier than your bit-shifting solution but, as long as you encapsulate either of them in a function, it shouldn't really matter.
I would suggest having a function along the lines of:
which would return a modified array by applying that power of 10.
Any even power of ten is a simple copy of bytes (since two nybbles is a byte) whilst only the odd powers of ten would need the tricky bit-shifting or remainder/division code.