java - How to convert byte array to hex string which it is using for convert it to long? -


i try convert byte[] long, got java.lang.numberformatexception.

this byte array wanna convert long

byte[] data = new byte[]{(byte) 0xdb, (byte) 0xa7, 0x53, (byte) 0xf8, (byte) 0xa8, 0x0c, 0x66, 0x8}; 

then try convert data hex string algorithm

public static string hexstringfromhexdata(byte[] data){         stringbuilder hexstring = new stringbuilder();          (byte subdata : data) {             string temp = integer.tohexstring(subdata & 0xff);             if (temp.length() == 1) {                 temp = "0" + temp;             }             hexstring.append(temp);         }          return hexstring.tostring();     } 

so got hexstring "dba753f8a80c6608"

with hexstring convert long below

string hexstring = "dba753f8a80c6608"; long value = long.parselong(hexstring.trim(), 16); 

it throw numberformatexception because hexstring exceed 7fffffffffffffff (long.max_value).

the right hexstring have "dba753f8a80c668" , hexstring able convert long value 989231983928329832l without exception.

we can try convert long value hex string

long value = 989231983928329832l string hexstring = long.tohexstring(value); 

the got hexstring "dba753f8a80c668" , if convert byte array same byte array data above.

so how convert byte[] data above hex string "dba753f8a80c668"?

is other algorithm convert byte[] data above , return correct long value 989231983928329832l?

======================================================================

simple step reproduce:

  1. 989231983928329832 convert byte[] data

  2. convert byte[] data long value 989231983928329832l

your byte array incorrect.

    byte[] data = new byte[]{(byte) 0xdb, (byte) 0xa7, 0x53, (byte) 0xf8, (byte) 0xa8, 0x0c, 0x66, 0x8};     long = 989231983928329832l;     byte[] bytes = bytebuffer.allocate(8).putlong(a).array();     for(int = 0; i<8; i++){         system.out.printf("%02x\t%02x\n", data[i], bytes[i]);     }     system.out.println(long.parselong(hexstringfromhexdata(bytes), 16)); 

which outputs.

db 0d

a7 ba

53 75

f8 3f

a8 8a

0c 80

66 c6

08 68

989231983928329832

the first column byte array, second column 1 created. can see string technique works correct byte array.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -