Java byte array conversion error

I have a string that contains a series of bits (for example, "01100011") and some integers in a while loop. For instance:

while (true) { int i = 100; String str = Input Series of bits // Convert i and str to byte array } 

Now I want a good quick way to convert a string and int to an array of bytes. So far, what I have done is converting int to String , and then applying the getBytes() method to both strings. However, it is a bit slow. Is there any other way to do that (maybe) faster than that?

+6
source share
3 answers

You can use Java class ByteBuffer

Example

 byte[] bytes = ByteBuffer.allocate(4).putInt(1000).array(); 
+7
source

Converting an int is easy (small number):

 byte[] a = new byte[4]; a[0] = (byte)i; a[1] = (byte)(i >> 8); a[2] = (byte)(i >> 16); a[3] = (byte)(i >> 24); 

Converting the string, first convert to an integer with Integer.parseInt(s, 2) , and then do it. Use Long if your bit string can be up to 64 bits, and BigInteger if it will be even larger.

+2
source

For int

 public static final byte[] intToByteArray(int i) { return new byte[] { (byte)(i >>> 24), (byte)(i >>> 16), (byte)(i >>> 8), (byte)i}; } 

For string

 byte[] buf = intToByteArray(Integer.parseInt(str, 2)) 
+1
source

Source: https://habr.com/ru/post/912641/


All Articles