1

I'm trying to convert byte array which holds hex values.

byte[] bytes = {48, 48, 48, 48, 48, 51, 51, 99}

for example : 48, 48, 48, 48, 48, 51, 51, 99 is 0000033c and converted to int is 828. The only way to convert is converting it to String and then parse integer from String.

 public static int ConvertValueFromBytes(byte[] bytes)
    {
        String b = new String(bytes);
        return Converter.ConvertHexToInt(b);
    }

The main problem here is performance, calling it many times can cause performance issues. When trying parse int value from byte array I get massive numbers, thats why I'm parsing from String, to get the correct value. Is there a better way or solution to this ?

5
  • 1
    Something doesn't add up in your logic. Why are you storing what is essentially a string representation of a hexadecimal value in a byte array? Your byte array should probably look like this: byte[] bytes = {0, 0, 3, 60}, or even just {3, 60}. Commented Sep 25, 2018 at 7:57
  • Possible duplicate of: stackoverflow.com/questions/9655181/… Commented Sep 25, 2018 at 7:57
  • I have a large one string hex value which contains up to 2000+ characters. What I'm doing is splitting them to smaller parts to get the int value. Commented Sep 25, 2018 at 8:00
  • @TimBiegeleisen I don't need String value, I need int. Commented Sep 25, 2018 at 8:02
  • There's no need to base yourself on the character values of your hex string. Every two characters represent one byte, so you should parse them as such. Commented Sep 25, 2018 at 8:02

1 Answer 1

1

Whilst it's very unclear why you would represent the data in this way, it's easy to transform without using a string:

int v = 0;
for (byte b : bytes) {
  v = 16 * v + Character.getNumericValue(b);
}

Ideone demo

Sign up to request clarification or add additional context in comments.

2 Comments

This kind of works and parsing negative values as well. Can you explain me please how this for loop works ?
0x123 is (((1) * 16 + 2) * 16) + 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.