I am trying to pass a String value in socket to another server. The other server should receive the value in hex format.
i.e If my String is s = "600185838e" at the server it should receive as 60 01 85 83 8e, but these values what I sent are been converted to ASCII & is not in the desired format.
I am using socket connection
BufferedWriter wr = new BufferedWriter(new OutputStreamWrit开发者_JAVA百科er(this.socket.getOutputStream()));
wr.write(messageBody);
wr.flush();
How can I send my String value similar as Hex value?
Thanking you all in advance
You should convert the hex string to byte array and then send it as byte array:
OutputStream out = this.socket.getOutputStream();
out.write(yourBytearray);
This is the method for converting the hex string to byte[] this is a copy from the link I gave, but I copied it here to make clear what I'm talking about:
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) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
You can also try splitting the string into 2-character long Strings and convert them to individual bytes via Byte.parseByte(my2CharString , 16) and then send them
Here's some code that will do what you want, just replace System.out.println() with write() <- must write only one byte:
String output = "ffee101";
while(output.length() > 0){
String byteToWrite;
if(output.length() <= 2){
byteToWrite = output;
output = "";
}
else{
byteToWrite = output.substring(0,2);
output = output.substring(2);
}
byte b = (byte)Short.parseShort(byteToWrite, 16);
System.out.println(b);
}
精彩评论