i have problem, method not work expected. in cases works. there case not work. have byte array containing values. in hex e.g.: 0x04 0x42 (littleendian). if use method converttwobytestoint, small number. should > 16000 , not smaller 2000.
i have 2 methods:
private static int converttwobytestoint(byte[] a){ string f1 = convertbytetohex(a[0]); string f2 = convertbytetohex(a[1]); return integer.parseint(f2+f1,radix16); } private static byte[] convertinttotwobyte(int value){ byte[] bytes = bytebuffer.allocate(4).putint(value).array(); system.out.println("check: "+arrays.tostring(bytes)); byte[] result = new byte[2]; //big little endian: result[0] = bytes[3]; result[1] = bytes[2]; return result; }
i call them follows:
byte[] h = convertinttotwobyte(16000); system.out.println("ats: "+arrays.tostring(h)); system.out.println("tbtint: "+converttwobytestoint(h));
if use value 16000, there no problem, if use 16900, integer value of "converttwobytestoint" 1060.
any idea?
based on example provided, guess convertbytetohex(byte)
converting single-digit hex string when byte value less 0x10. 16900 0x4204 , 1060 0x424.
you need ensure conversion zero-padded 2 digits.
a simpler approach use bit manipulation construct int
value bytes:
private static int converttwobytestoint(byte[] a) { return ((a[1] & 0xff) << 8) | (a[0] & 0xff); }
Comments
Post a Comment