Using a byte array as Map key

It’s okay so long as you only want reference equality for your key – arrays don’t implement “value equality” in the way that you’d probably want. For example: byte[] array1 = new byte[1]; byte[] array2 = new byte[1]; System.out.println(array1.equals(array2)); System.out.println(array1.hashCode()); System.out.println(array2.hashCode()); prints something like: false 1671711 11394033 (The actual numbers are irrelevant; the fact that …

Read more

Put byte array to JSON and vice versa

Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value. Apache commons offers good utilities: byte[] bytes = getByteArr(); String base64String …

Read more

How to convert a Java String to an ASCII byte array?

Using the getBytes method, giving it the appropriate Charset (or Charset name). Example: String s = “Hello, there.”; byte[] b = s.getBytes(StandardCharsets.US_ASCII); If more control is required (such as throwing an exception when a character outside the 7 bit US-ASCII is encountered) then CharsetDecoder can be used: private static byte[] strictStringToBytes(String s, Charset charset) throws …

Read more

When to use []byte or string in Go?

My advice would be to use string by default when you’re working with text. But use []byte instead if one of the following conditions applies: The mutability of a []byte will significantly reduce the number of allocations needed. You are dealing with an API that uses []byte, and avoiding a conversion to string will simplify …

Read more

How to create bitmap from byte array?

You’ll need to get those bytes into a MemoryStream: Bitmap bmp; using (var ms = new MemoryStream(imageData)) { bmp = new Bitmap(ms); } That uses the Bitmap(Stream stream) constructor overload. UPDATE: keep in mind that according to the documentation, and the source code I’ve been reading through, an ArgumentException will be thrown on these conditions: …

Read more

Is there an equivalent to memcpy() in Java?

Use System.arraycopy() System.arraycopy(sourceArray, sourceStartIndex, targetArray, targetStartIndex, length); Example, String[] source = { “alpha”, “beta”, “gamma” }; String[] target = new String[source.length]; System.arraycopy(source, 0, target, 0, source.length); or use Arrays.copyOf() Example, target = Arrays.copyOf(source, length); java.util.Arrays.copyOf(byte[] source, int length) was added in JDK 1.6. The copyOf() method uses System.arrayCopy() to make a copy of the array, …

Read more