0
votes

I am working on Socket connection. I am working on the client side. I have gone through this discussion Socket pass value as Hex. I need to send the String e.g(0x01 is a hex value and a String "Ravi") at the server they are expecting hexa value like 1 72 61 76 69. I tried of converting String Ravi to hexa value as String and appending "1" and try to convert to byte array. I am getting an exception that StringIndexOutOfBound exception.

update:

`public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 2) + Character.digit(s.charAt(i+1), 16)); } return data; }

public String toHex(String arg) {
    return String.format("%x", new BigInteger(arg.getBytes()));
}`

I used these two methods to convert the 1Ravi string to byte array but i am getting exception hexstringtobytearray method.

1
Please show us what you've tried, including sample input. Note that you're not really trying to send it "in hex" - you're just trying to send bytes. - Jon Skeet

1 Answers

2
votes

try this

        Socket sock = new Socket("host", port);
    OutputStream out = sock.getOutputStream();
    out.write(0);
String s = "ravi";
    byte[] bytes = s.getBytes("UTF-8");
    out.write(bytes);