ByteBuffer to bigdecimal, binary, string

2019-07-01 14:14发布

问题:

**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.

回答1:

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:

byte[] data= new byte[] { 0x12, 0x04, 0x07, 0x05, 0x08, 0x11, 0x38, 0x44, 0x77, 0x33};
BigInteger bi =new BigInteger(1,data);
BigDecimal bd = new BigDecimal(bi);


回答2:

Your biggest hurdle is that String ONLY operates with char internally, so you'll need to convert somehow. A slightly cheaper way is

BigDecimal bd = new BigDecimal(new String[bigmyBuffer]);

Since 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.