将 int 转换为 BCD 字节数组
我想使用 BCD 将 int 转换为 byte[2] 数组。
所讨论的 int 将来自表示年份的 DateTime,并且必须转换为两个字节。
是否有任何预制函数可以执行此操作,或者您能给我一个简单的方法来执行此操作吗?
示例:
int year = 2010
将输出:
byte[2]{0x20, 0x10};
I want to convert an int to a byte[2] array using BCD.
The int in question will come from DateTime representing the Year and must be converted to two bytes.
Is there any pre-made function that does this or can you give me a simple way of doing this?
example:
int year = 2010
would output:
byte[2]{0x20, 0x10};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
请注意,您要求的是大端结果,这有点不寻常。
Beware that you asked for a big-endian result, that's a bit unusual.
使用这个方法。
这本质上就是它的工作原理。
(一种优化是预先将每个字节设置为 0 —— 这是 .NET 在分配新的字节时隐式完成的。数组 - 并在值达到 0 时停止迭代。为了简单起见,上面的代码中没有进行后一种优化。此外,如果可用,一些编译器或汇编器提供了除法/求余例程,允许检索 中的商和余数。一个除法步骤,但通常不需要进行优化。)
Use this method.
This is essentially how it works.
(One optimization is to set every byte to 0 beforehand -- which is implicitly done by .NET when it allocates a new array -- and to stop iterating when the value reaches 0. This latter optimization is not done in the code above, for simplicity. Also, if available, some compilers or assemblers offer a divide/remainder routine that allows retrieving the quotient and remainder in one division step, an optimization which is not usually necessary though.)
这是一个可怕的暴力版本。我确信有比这更好的方法,但无论如何它应该有效。
可悲的是,x86 微处理器架构中内置了快速二进制到 BCD 转换(如果您能做到的话)!
Here's a terrible brute-force version. I'm sure there's a better way than this, but it ought to work anyway.
The sad part about it is that fast binary to BCD conversions are built into the x86 microprocessor architecture, if you could get at them!
这是一个稍微干净的版本,然后 Jeffrey 的
Here is a slightly cleaner version then Jeffrey's
也许是一个包含此循环的简单解析函数
maybe a simple parse function containing this loop
更常见的解决方案
More common solution
与 Peter O. 版本相同,但在 VB.NET 中
这里的技巧是要注意,简单地使用 pValue /= 10 将会对值进行四舍五入,因此如果参数是“16”,则字节的第一部分将是正确的,但除法的结果将为 2(因为 1.6 将向上舍入)。因此我使用 Math.Floor 方法。
Same version as Peter O. but in VB.NET
The trick here is to be aware that simply using pValue /= 10 will round the value so if for instance the argument is "16", the first part of the byte will be correct, but the result of the division will be 2 (as 1.6 will be rounded up). Therefore I use the Math.Floor method.
我在 IntToByteArray 上发布了一个通用例程,您可以使用它,例如:
varyearInBytes = ConvertBigIntToBcd(2010, 2) ;
I made a generic routine posted at IntToByteArray that you could use like:
var yearInBytes = ConvertBigIntToBcd(2010, 2);