0

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.

Community
  • 1
  • 1
Ravi Teja N
  • 5
  • 1
  • 4
  • 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 Nov 27 '12 at 07:03

1 Answers1

2

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);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • thanks for the reply.. I need to send in the form of bytes. I tried the Hex String to byte array. I am getting StringOutOfIndexBound Exception. – Ravi Teja N Nov 27 '12 at 06:47
  • @RaviTejaN: Please show us the code you've tried. Clearly you're doing something wrong (otherwise you wouldn't get an exception), but we can't tell *what* you're doing wrong without seeing your code. – Jon Skeet Nov 27 '12 at 07:02
  • for iphone there we are using framebuffer to send the data through socket.But i don't know how to achieve this in android. – Ravi Teja N Nov 27 '12 at 09:51
  • thanks Evgeniy for the help. My problem is solved. Thanks once again. – Ravi Teja N Nov 27 '12 at 12:16