ByteBuffer 到 bigdecimal、二进制、字符串
**请检查本文底部的编辑
我有一个字节缓冲区 [128 位] [其中有数字],我需要将其转换为大十进制、二进制、字符串,因为这些是使用 jdbc 时相应的 sql 映射。
我可以使用库 API 来执行此操作吗?我看到 String.valueof() 不接受字节数组作为参数。所以我坚持做这样的事情:
BigDecimal bd = new BigDecimal(bigmyBuffer.asCharBuffer().toString());
这对我来说看起来像是一个黑客?有没有更好的方法来执行此操作,或者更确切地说以有效的方式执行 jdbc 部分。到目前为止,我专注于在相应的 sql 列中进行插入。
编辑:
我错了,字节缓冲区不仅仅是数字,而是各种位。所以现在我需要获取 128 位字节缓冲区并将其转换为 2 个 long,然后合并为一个 bigdecimal,以便数字保持其完整性。所以像这样: LongBuffer lbUUID = guid.asLongBuffer();
firstLong= lbUUID.get();
secondLong = lbUUID.get();
BigDecimal = firstLong + secondLong ;
谢谢。
**Please check the edit at the bottom of this post
I have a bytebuffer[128 bits] [which has numbers] which I need to convert to bigdecimal, binary, string since these are the corresponding sql mapping while using jdbc.
Is there a library API that I can make use of to do this. I see String.valueof() does not take a byte array as a parameter.So I am stuck to doing something like this:
BigDecimal bd = new BigDecimal(bigmyBuffer.asCharBuffer().toString());
This looks like a hack to me ?. Is there a better way of doing this or rather doing the jdbc part in an efficient manner. I am focused on doing inserts in the respective sql columns as of now.
Edit:
I was wrong , the bytebuffers were not just numbers but all sort of bits. So now I need to take the 128 bit byte buffer and convert it to 2 longs and then merge to a bigdecimal so that the numbers maintain their sanity. So something like this:
LongBuffer lbUUID = guid.asLongBuffer();
firstLong= lbUUID.get();
secondLong = lbUUID.get();
BigDecimal = firstLong + secondLong ;
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好绕道 BigInteger?使用 BigInteger,您可以将字节数组解释为正大数,并且从 BigInteger 到 BigDecimal 只迈出了很小的一步:
May it is better to detour over BigInteger? Using BigInteger you can interpretate a byte-array as positive large number and from BigInteger it is a very small step to BigDecimal:
您最大的障碍是
String
仅在内部与char
一起操作,因此您需要以某种方式进行转换。一个稍微便宜的方法是因为你只有数字,所以你不必担心这里的字符集。不幸的是,这仍然会创建一个临时 String 对象。
唯一的选择是手动解析字节缓冲区(即逐字节遍历它,并以这种方式初始化 BigDecimal) - 这将避免分配任何临时对象,但最终会导致更多的函数调用,因此您可能不这样做除非您真的想避免创建该字符串,否则不想走这条路。
我不知道更多关于您的应用程序的上下文,所以我不确定您的 BigDecimal 到底是如何使用的。
Your biggest hurdle is that
String
ONLY operates withchar
internally, so you'll need to convert somehow. A slightly cheaper way isSince you only have digits, you won't have to worry about charsets here. Unfortunately, this will still create a temporary String object.
The only alternative is to parse the byte buffer manually (i.e. go through it, byte by byte, and initialize your BigDecimal that way) - that will avoid allocating any temporary objects, but ends up in a lot more function calls, so you probably don't want to go that route unless you're really trying to avoid creating that String.
I don't know more about the context of your application, so I'm not sure how exactly your BigDecimal is used.