简体   繁体   中英

Write Hex string in Socket Communication in android

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 eg(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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM