Suppose I have the IP stored in a String:
String ip = "192.168.2.1"
and I want to get the byte array with the four ints. How can I do it? Thanks!
A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.
How to convert String to byte[] in Java? In Java, we can use str. getBytes(StandardCharsets. UTF_8) to convert a String into a byte[] .
Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.
Something like this:
InetAddress ip = InetAddress.getByName("192.168.2.1");
byte[] bytes = ip.getAddress();
for (byte b : bytes) {
System.out.println(b & 0xFF);
}
Each number is a byte, so in your case the appropriate byte[] would be { 192, 168, 2, 1 }.
To be more specific, if you have the string, you first have to split it by the "."s and then parse a byte from each resulting string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With