Last active
November 27, 2017 20:00
-
-
Save lWeRl/4e4252d6a704de0bea9b57c7ccb4d71b to your computer and use it in GitHub Desktop.
Parse int to byte array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.Arrays; | |
/** | |
* Created by lWeRl on 27.11.2017. | |
*/ | |
public class IntToByteArray { | |
public static void main(String[] args) throws IOException { | |
ByteArrayInputStream bais = new ByteArrayInputStream(parseInt(12345)); | |
DataInputStream dis = new DataInputStream(bais); | |
System.out.println(dis.readInt()); | |
} | |
public static byte[] parseInt(int i) { | |
String binary = String.format("%32s", Integer.toBinaryString(i)).replace(' ', '0'); | |
byte[] result = new byte[4]; | |
for (int j = 0; j < 4; j++) { | |
String part = binary.substring(j * 8, j * 8 + 8); | |
result[j]= (byte) Integer.parseInt(part, 2); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment