How do we choose to use a string or a number above? Explains the benefits of using numeric types, so the question is, how do you convert between numeric types and byte arrays?
Let's take a look at the conversion between a single numeric type and a byte array, as an example of an integer type:
public static byte[] Inttobytes (int x) {Bytebuffer Intbuffer = bytebuffer.allocate (integer.bytes); Intbuffer.putint (0, X); return Intbuffer.array ();} public static int bytestoint (byte[] bytes) {return bytestoint (bytes, 0, bytes.length);} public static int bytestoint (byte[] bytes, int offset, int length) {Bytebuffer Intbuffer = bytebuffer.allocate (Integer . BYTES); Intbuffer.put (bytes, offset, length); Intbuffer.flip (); return Intbuffer.getint ();}
Let's look at the conversions between multiple numeric types and byte arrays, with the example of converting between a long and a byte array:
Public static byte[] longsettobytes (Collection<long> ids) { Int len = ids.size () *long.bytes; bytebuffer bytebuffer = Bytebuffer.allocate (len); int start = 0; for (Long id : ids) { bytebuffer.putlong (start, id); start += Long.BYTES; } return bytebuffer.array ();} Public static set<long> bytestolongset (byte[] bytes) { return bytestolongset (bytes, 0, bytes.length);} Public static set<long> bytestolongset (Byte[] bytes, int offset, int length) { set<long> ids = new hashset<> (); byteBuffer bytebuffer = bytebuffer.allocate (length); bytebuffer.put (Bytes, offset, length); bytebuffer.flip (); int count = length/long.bytes; for (int i=0; i<count; i++) { ids.add (Bytebuffer.getlong ()); } return ids;}
Since Bytebuffer supports 5 numeric types, we provide complete support for conversions between numeric types and byte arrays, as shown in:
Conversion between a numeric type and a byte array