Re: [問題] bytes轉integer (ByteOrder Issue)
※ 引述《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
java 近期熱門文章
PTT數位生活區 即時熱門文章