java中float與byte[]的互轉(zhuǎn)
起因:想把一個float[]轉(zhuǎn)換成內(nèi)存數(shù)據(jù),查了一下,下面兩個方法可以將float轉(zhuǎn)成byte[]。方法一
Java代碼:
- import java.nio.ByteBuffer;
- import java.util.ArrayList;
- float buffer = 0f;
- ByteBuffer bbuf = ByteBuffer.allocate(4);
- bbuf.putFloat(buffer);
- byte[] bBuffer = bbuf.array();
- bBuffer=this.dataValueRollback(bBuffer);
- //數(shù)值反傳
- private byte[] dataValueRollback(byte[] data) {
- ArrayList<Byte> al = new ArrayList<Byte>();
- for (int i = data.length - 1; i >= 0; i--) {
- al.add(data[i]);
- }
- byte[] buffer = new byte[al.size()];
- for (int i = 0; i <= buffer.length - 1; i++) {
- buffer[i] = al.get(i);
- }
- return buffer;
- }
方法二
先用 Float.floatToIntBits(f)轉(zhuǎn)換成int
再通過如下方法轉(zhuǎn)成byte []
參考自站長網(wǎng)http://www.software8.co/wzjs/java/2548.html
參考自站長網(wǎng)http://www.software8.co/wzjs/java/2548.html
Java代碼:
- /**
- * 將int類型的數(shù)據(jù)轉(zhuǎn)換為byte數(shù)組 原理:將int數(shù)據(jù)中的四個byte取出,分別存儲
- *
- * @param n int數(shù)據(jù)
- * @return 生成的byte數(shù)組
- */
- public static byte[] intToBytes2(int n) {
- byte[] b = new byte[4];
- for (int i = 0; i < 4; i++) {
- b[i] = (byte) (n >> (24 - i * 8));
- }
- return b;
- }
- /**
- * 將byte數(shù)組轉(zhuǎn)換為int數(shù)據(jù)
- *
- * @param b 字節(jié)數(shù)組
- * @return 生成的int數(shù)據(jù)
- */
- public static int byteToInt2(byte[] b) {
- return (((int) b[0]) << 24) + (((int) b[1]) << 16)
- + (((int) b[2]) << 8) + b[3];
- }