简体   繁体   English

如何在java中将字符串转换为bcd格式的字节数组?

[英]How to convert a string to byte array in bcd format in java?

I have the next string:我有下一个字符串:

String points = "210987654321";

and I need to end up in the 6 byte array in bcd format which looks like this (same digits):我需要以 bcd 格式结束 6 字节数组,它看起来像这样(相同的数字):

byte [] result = { 0x21, 0x09, (byte) 0x87, 0x65, 0x43, 0x21 };

How do I get there?我如何到达那里? points.getBytes(); gives not what I need.不给我需要的。

Based on the code you provided and its expected output it looks like you're trying to convert into the BCD format (BCD is a rather generic definition) normally used to represent a string in which each letter represents a HEX digit into its corresponding byte representation (from comments to this answer: "packed BCD").根据您提供的代码及其预期输出,您似乎正在尝试转换为 BCD 格式(BCD 是一个相当通用的定义),通常用于表示一个字符串,其中每个字母代表一个 HEX 数字到其相应的字节表示中(从对此答案的评论:“打包 BCD”)。

There are solutions in StackOverflow, such as the following: StackOverflow 中有解决方案,例如:

In the interest of "not reinventing the wheel", however, I would favour functionality available in libraries like Apache Commons or Google Guava:然而,为了“不重新发明轮子”,我更喜欢 Apache Commons 或 Google Guava 等库中可用的功能:

For Apache Commons it boils down to roughly this code:对于 Apache Commons,它大致可以归结为以下代码:

byte[] result = Hex.decodeHex(points)

It is to be noted however that the above code will accept as inputs also strings containing letters up to the letter "F" so if that's not acceptable to you, you will have to make sure that your string only contains numbers.但是需要注意的是,上面的代码也接受包含字母“F”以内字母的字符串作为输入,因此如果您不能接受,则必须确保您的字符串只包含数字。


As BCD comprises a number of variants, I believe it's worth mentioning that before applying a BCD conversion you should determine which specific conversion you want to apply based on your software's purposes.由于 BCD 包含许多变体,我认为值得一提的是,在应用 BCD 转换之前,您应该根据软件的用途确定要应用的特定转换。

In the financial/services sector, for example, it's very common the need to convert into the EBCDIC format ( http://ascii-table.com/ebcdic-table.php ) to interact with IBM systems.例如,在金融/服务领域,转换为 EBCDIC 格式 ( http://ascii-table.com/ebcdic-table.php ) 以与 IBM 系统交互的需求非常普遍。 In such case I recommend checking the following StackOverflow question and its related answers:在这种情况下,我建议检查以下 StackOverflow 问题及其相关答案:


Finally, if you really meant converting into another BCD format, you may have write your own code based the rules governing your specific BCD format.最后,如果您真的想转换成另一种 BCD 格式,您可能已经根据管理特定 BCD 格式的规则编写了自己的代码。 Before you start coding, of course, I still recommend looking for libraries performing the conversion for you.当然,在您开始编码之前,我仍然建议您寻找为您执行转换的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM