Java 将 4 个字节转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2840190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Convert 4 bytes to int
提问by iTEgg
i was wondering if the solution for this documented hereis still the solution or is there any other way getting an int from 4 bytes?
我想知道这里记录的解决方案是否仍然是解决方案,还是有其他方法可以从 4 个字节获取 int?
thank you.
谢谢你。
EDIT: im getting the byte[] from sockets .read
编辑:我从套接字 .read 获取字节 []
EDIT: int recvMsgSize = in.read(Data, 0, BufferSize);
if recvMsgSize is -1 i know the connection has been dropped.
编辑:int recvMsgSize = in.read(Data, 0, BufferSize);
如果 recvMsgSize 为 -1,我知道连接已断开。
how do i detect this when im using DataInputStream instead of InputStream?
当我使用 DataInputStream 而不是 InputStream 时,我如何检测到这一点?
thanks.
谢谢。
EDIT: apologies for being a yoyo regarding accepting the right answer. but after mihi's updated final response, it would appear that the method is solid and cuts down extended coding and in my opinion best practice.
编辑:对于接受正确答案的悠悠球,我深表歉意。但是在 mihi 更新的最终响应之后,该方法似乎是可靠的,并且减少了扩展编码,在我看来是最佳实践。
采纳答案by mihi
Depending on where you get those 4 bytes from:
取决于您从何处获取这 4 个字节:
http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#readInt()
http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#readInt()
http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#getInt(int)
http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#getInt(int)
You can of course still do it manually, but in most cases using one of those (if you have to convert a byte array with lots of bytes, you might want to use a DataInputStream
around a ByteArrayInputStream
for example) is easier.
当然,您仍然可以手动执行此操作,但在大多数情况下,使用其中之一(如果您必须转换包含大量字节的字节数组,例如您可能希望使用 aDataInputStream
周围ByteArrayInputStream
)更容易。
Edit: If you need to change the endianness, you will have to use a ByteBuffer, or reverse the bytes yourself, or do the conversion yourself, as DataInput does not support changing the endianness.
编辑:如果您需要更改字节顺序,则必须使用 ByteBuffer,或者自己反转字节,或者自己进行转换,因为 DataInput 不支持更改字节顺序。
Edit2: When you get them from the socket input stream, I'd wrap that one into a DataInputStream
and use it for reading all kinds of data. Especially since InputStream.read(byte[]) will not guarantee to fill the whole byte array... DataInputStream.readFully does.
Edit2:当您从套接字输入流中获取它们时,我DataInputStream
会将其包装为 a并使用它来读取各种数据。特别是因为 InputStream.read(byte[]) 不能保证填充整个字节数组...... DataInputStream.readFully 确实如此。
DataInputStream in = new DataInputStream(socket.getInputStream());
byte aByte = in.readByte();
int anInt = in.readInt();
int anotherInt = in.readInt();
short andAShort = in.readShort(); // 11 bytes read :-)
byte[] lotOfBytes = new byte[anInt];
in.readFully(lotOfBytes);
Edit3: When reading multiple times from a stream, they will continue reading where you stopped, i. e. aByte will be byte 0, anInt will be bytes 1 to 4, anotherInt will be bytes 5 to 8, etc. readFully will read on after all that and will block until it has read lotOfbytes
.
Edit3:当从一个流中多次读取时,他们将继续读取你停止的地方,即 aByte 将是字节 0,anInt 将是字节 1 到 4,anotherInt 将是字节 5 到 8,等等。 readFully 将在所有之后继续读取并且会阻塞直到它读取lotOfbytes
。
When the stream stops (the connection drops) you will get EOFException
instead of -1, so if you get -1, the int really was -1.
当流停止(连接断开)时,您将获得EOFException
而不是 -1,因此如果您获得 -1,则 int 确实是 -1。
If you do not want to parse any bytes at all, you can skip() them. Parsing one byte in 2 different ways is not possible with DataInputStream (i. e. read first an int from byte 0 to 3, then one from byte 2 to 5), but usually not needed either.
如果你根本不想解析任何字节,你可以跳过()它们。DataInputStream 无法以两种不同的方式解析一个字节(即首先从字节 0 到 3 读取一个 int,然后从字节 2 到 5 读取一个 int),但通常也不需要。
Example:
例子:
// read messages (length + data) until the stream ends:
while (true) {
int messageLength;
try {
messageLength = in.readInt(); // bytes 0 to 3
} catch (EOFException ex) {
// connection dropped, so handle it, for example
return;
}
byte[] message = new byte[messageLength];
in.readFully(message);
// do something with the message.
}
// all messages handled.
Hope this answers your additional questions.
希望这能回答您的其他问题。
回答by polygenelubricants
You have to be very careful with any widening conversion and numeric promotion, but the code below converts 4 byte
into int
:
您必须非常小心任何扩大转换和数字提升,但下面的代码将 4 转换byte
为int
:
byte b1 = -1;
byte b2 = -2;
byte b3 = -3;
byte b4 = -4;
int i = ((0xFF & b1) << 24) | ((0xFF & b2) << 16) |
((0xFF & b3) << 8) | (0xFF & b4);
System.out.println(Integer.toHexString(i)); // prints "fffefdfc"
See also
也可以看看
- Java code To convert byte to Hexadecimal
- Pay attention to the need to mask with
& 0xFF
-- you'll probably end up doing a lot of this if you're working withbyte
since all arithmetic operations promote toint
(orlong
)
- Pay attention to the need to mask with
- Java代码将字节转换为十六进制
- 注意掩码的必要性
& 0xFF
- 如果您正在使用,您可能最终会做很多这样的事情,byte
因为所有算术运算都提升到int
(或long
)
- 注意掩码的必要性
回答by bgw
As mihi said, it depends on where you are getting those bytes from, but this code might be of use:
正如 mihi 所说,这取决于您从何处获取这些字节,但此代码可能有用:
int myNumber = (((int)byteOne) << 0) |
(((int)byteTwo) << 8) |
(((int)byteThree) << 16) |
(((int)byteFour) << 24);
回答by Roman
A solution in functional style (just for variety, imho not very convinient in use):
功能风格的解决方案(仅用于多样性,恕我直言在使用中不太方便):
private int addByte (int base, byte appendix) {
return (base << 4) + appendix;
}
public void test() {
byte b1 = 5, b2 = 5, byte b3 = 0, b4 = 1;
int result = addByte (addByte (addByte (addByte (0, b1), b2), b3), b4);
}
回答by Cowan
If you have them already in a byte[]
array, you can use:
如果您已经将它们放在byte[]
数组中,则可以使用:
int result = ByteBuffer.wrap(bytes).getInt();
or, if you have Google's guava-librarieson your classpath, you have the shortcut:
或者,如果你的类路径上有谷歌的番石榴库,你有快捷方式:
int result = Ints.fromByteArray(array);
which has the advantage that you have similarly nice APIs for other types (Longs.fromByteArray
, Shorts.fromByteArray
, etc).
它的优点是你有其他类型(同样不错的API Longs.fromByteArray
,Shorts.fromByteArray
等等)。