作者qrtt1 (隐者)
看板java
标题Re: [问题] bytes转integer (ByteOrder Issue)
时间Fri Jun 2 11:39:09 2006
※ 引述《Dancer31 (:p)》之铭言:
: ※ 引述《PsMonkey (痞子军团团长)》之铭言:
: : Java 本来就是用 4byte 来处理一个 int... Orz
: : 目前看来最快而且最健.... 康的做法是...
: : return new BigInteger(bytes).intValue();
: : 哈哈哈哈... [逃]
: BigInteger(byte[] val)要求的byte是Big-endian order
: 刚好跟我要的相反orz
请注意您资料的来源啊
java预设的ByteOrder是BigEndien
如果是c(大部分平台)或是某些binary file spec有特别注明
则为Little的:)
: 我找到一篇文章刚好有我要的函式
: 也解决我的问题
: private final byte w[] = new byte[8];
: public synchronized int readInt() throws IOException
: {
: this.in.readFully(w, 0, 4);
: return (w[3]) << 24
: | (w[2] & 0xff) << 16
: | (w[1] & 0xff) << 8
: | (w[0] & 0xff);
: }
: 原文出处
: http://www.javaworld.com.tw/jute/post/view?bid=29&id=49582&sty=3
: 想请问一下为什麽要加上 & 0xff阿?
: 和0xff做and出来的值不就跟原本一样吗?
呵,文章上面写"不想用nio的话才自己写啊"
nio大致上是这样用...
(不知有没有更好的写法,因为俺自己看api拼出来的,也许有多余的code)
http://rafb.net/paste/results/FlorUq25.html [code]
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class ByteOrderExample {
public static void main(String[] args) throws IOException {
FileInputStream fs = new FileInputStream(new File("c:\\intdata"));
byte[] four = new byte[4];
fs.read(four);
System.out.println(ByteBuffer.wrap(four).order(ByteOrder.LITTLE_ENDIAN)
.asIntBuffer().get());
fs.close();
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 163.26.34.214