简体   繁体   English

给java中的十六进制整数带来很大的价值?

[英]Integer to hex in java giving very big value?

I am actually reading int values from the java socket bufferedread and later converting into hex representation. 我实际上是从java套接字bufferedread读取int值,然后转换为十六进制表示形式。 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? 只有我一个或两个数据,在转换成十六进制后的正常情况下,它们是BE或A9,但我却得到ffdd,整数值为65533。这可能是我的转换方法有误还是输入值是它本身具有那个值?

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. 目前尚不清楚您要做什么,但是按照文档中的定义,读取的返回值是:读取的字符,为0到65535(0x00-0xffff)范围内的整数,如果结尾为-1,则返回-1。流已到达。

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 '\' (or 0) and a maximum value of '\￿' (or 65,535 inclusive). ) 您以为自己正在读取字节,但是由于使用的是BufferedReader,因此实际上可以读取chars( char数据类型是单个16位Unicode字符。其最小值为'\\ u0000'(或0),最大值为'\\ uffff'(或65,535(含))。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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