Java – How do I receive socket input in hexadecimal?

How do I receive socket input in hexadecimal?… here is a solution to the problem.

How do I receive socket input in hexadecimal?

I sent a GET message over a socket. I received a response message as a string. But I want to receive in hexadecimal form. But I didn’t implement it. Here is my code block as a string. Can you help me?

                    dos = new DataOutputStream(socket.getOutputStream());
                    dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));

dos.write(requestMessage.getBytes());
                    String data = "";                       
                    StringBuilder sb = new StringBuilder();
                    while ((data = dis.readLine()) != null) {
                            sb.append(data);
                    }

Solution

When you use BufferedReader, you get input in String format: So a better way to use InputStream….

This is sample code to achieve this.

        InputStream in = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] read = new byte[1024];
        int len;
        while((len = in.read(read)) > -1) {
            baos.write(read, 0, len);
        }
         this is the final byte array which contains the data
         read from Socket
        byte[] bytes = baos.toByteArray();

After getting byte[], you can use the following function to convert it to a hexadecimal string

StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
    sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());// here sb is hexadecimal string

Quoted from java-code-to-convert-byte-to-hexadecimal

Related Problems and Solutions