Reputation: 753
I am actually reading int values from the java socket bufferedread and later converting into hex representation. I am using a method as below.
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(nextChar));
if (sb.length() < 2) {
sb.insert(0, '0'); //pad with leading zero if needed
}
String hexChar = sb.toString();
System.out.println("\n\n hex value is "+hexChar +" "+"Int value is:"+nextChar);
The codes are working fine. Only I got one or two data which in normal case after conversion into hex is either BE or A9 but I am getting ffdd and the integer value is 65533. Could it be my conversion method is wrong or is it input value is it self is having that value?
Upvotes: 0
Views: 257
Reputation: 401
It's not really clear what you're trying to do, but as defined in the documentation the return from read is: The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached.
This is of course because you are using a text reader.
You might want to read this answer.
OK, Got it.
You thought you are reading bytes, but since you are using BufferedReader you actually read chars (The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).)
I believe that this is what you wanted to achieve. Please note this is not the best way, its just a sample!
InputStream is = sock.getInputStream()
BufferedInputStream bis = new BufferedInputStream(is);
int nextByte;
StringBuilder sb = new StringBuilder();
while( (nextByte = bis.read()) != -1 ) {
sb.append(String.format("%02X ", nextByte));
}
Upvotes: 1