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 ?

MINIKAS
  • 57
  • 7
  • 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}`. – Robby Cornelissen Sep 25 '18 at 07:57
  • Possible duplicate of: https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java – Tim Biegeleisen Sep 25 '18 at 07: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. – MINIKAS Sep 25 '18 at 08:00
  • @TimBiegeleisen I don't need String value, I need int. – MINIKAS Sep 25 '18 at 08: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. – Robby Cornelissen Sep 25 '18 at 08:02

1 Answers1

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

Andy Turner
  • 137,514
  • 11
  • 162
  • 243