Java字節(jié)序
http://origin100.iteye.com/blog/267165
?
/**
* 通信格式轉(zhuǎn)換
*
* Java和一些windows編程語言如c、c++、delphi所寫的網(wǎng)絡(luò)程序進(jìn)行通訊時,需要進(jìn)行相應(yīng)的轉(zhuǎn)換
* 高、低字節(jié)之間的轉(zhuǎn)換
* windows的字節(jié)序?yàn)榈妥止?jié)開頭
* linux,unix的字節(jié)序?yàn)楦咦止?jié)開頭
* java則無論平臺變化,都是高字節(jié)開頭*/ public class FormatTransfer {
/*** 將int轉(zhuǎn)為低字節(jié)在前,高字節(jié)在后的byte數(shù)組* @param n int* @return byte[]*/
public static byte[] toLH(int n) {byte[] b = new byte[4];b[0] = (byte) (n & 0xff);b[1] = (byte) (n >> 8 & 0xff);b[2] = (byte) (n >> 16 & 0xff);b[3] = (byte) (n >> 24 & 0xff);return b;
} /*** 將int轉(zhuǎn)為高字節(jié)在前,低字節(jié)在后的byte數(shù)組* @param n int* @return byte[]*/
public static byte[] toHH(int n) {byte[] b = new byte[4];b[3] = (byte) (n & 0xff);b[2] = (byte) (n >> 8 & 0xff);b[1] = (byte) (n >> 16 & 0xff);b[0] = (byte) (n >> 24 & 0xff);return b;
} /*** 將short轉(zhuǎn)為低字節(jié)在前,高字節(jié)在后的byte數(shù)組* @param n short* @return byte[]*/
public static byte[] toLH(short n) {byte[] b = new byte[2];b[0] = (byte) (n & 0xff);b[1] = (byte) (n >> 8 & 0xff);return b;
} /*** 將short轉(zhuǎn)為高字節(jié)在前,低字節(jié)在后的byte數(shù)組* @param n short* @return byte[]*/
public static byte[] toHH(short n) {byte[] b = new byte[2];b[1] = (byte) (n & 0xff);b[0] = (byte) (n >> 8 & 0xff);return b;
} /*** 將將int轉(zhuǎn)為高字節(jié)在前,低字節(jié)在后的byte數(shù)組 public static byte[] toHH(int number) {int temp = number;byte[] b = new byte[4];for (int i = b.length - 1; i > -1; i--) {b = new Integer(temp & 0xff).byteValue();temp = temp >> 8;}return b;
} public static byte[] IntToByteArray(int i) {byte[] abyte0 = new byte[4];abyte0[3] = (byte) (0xff & i);abyte0[2] = (byte) ((0xff00 & i) >> 8);abyte0[1] = (byte) ((0xff0000 & i) >> 16);abyte0[0] = (byte) ((0xff000000 & i) >> 24);return abyte0;
} */ /*** 將float轉(zhuǎn)為低字節(jié)在前,高字節(jié)在后的byte數(shù)組*/
public static byte[] toLH(float f) {return toLH(Float.floatToRawIntBits(f));
} /*** 將float轉(zhuǎn)為高字節(jié)在前,低字節(jié)在后的byte數(shù)組*/
public static byte[] toHH(float f) {return toHH(Float.floatToRawIntBits(f));
} /*** 將String轉(zhuǎn)為byte數(shù)組*/
public static byte[] stringToBytes(String s, int length) {while (s.getBytes().length < length) {s += " ";}return s.getBytes();
} /*** 將字節(jié)數(shù)組轉(zhuǎn)換為String* @param b byte[]* @return String*/
public static String bytesToString(byte[] b) {StringBuffer result = new StringBuffer("");int length = b.length;for (int i=0; i<length; i++) {result.append((char)(b & 0xff));}return result.toString();
} /*** 將字符串轉(zhuǎn)換為byte數(shù)組* @param s String* @return byte[]*/
public static byte[] stringToBytes(String s) {return s.getBytes();
} /*** 將高字節(jié)數(shù)組轉(zhuǎn)換為int* @param b byte[]* @return int*/
public static int hBytesToInt(byte[] b) {int s = 0;for (int i = 0; i < 3; i++) {if (b >= 0) {s = s + b;} else {s = s + 256 + b;}s = s * 256;}if (b[3] >= 0) {s = s + b[3];} else {s = s + 256 + b[3];}return s;
} /*** 將低字節(jié)數(shù)組轉(zhuǎn)換為int* @param b byte[]* @return int*/
public static int lBytesToInt(byte[] b) {int s = 0;for (int i = 0; i < 3; i++) {if (b[3-i] >= 0) {s = s + b[3-i];} else {s = s + 256 + b[3-i];}s = s * 256;}if (b[0] >= 0) {s = s + b[0];} else {s = s + 256 + b[0];}return s;
} /*** 高字節(jié)數(shù)組到short的轉(zhuǎn)換* @param b byte[]* @return short*/
public static short hBytesToShort(byte[] b) {int s = 0;if (b[0] >= 0) {s = s + b[0];} else {s = s + 256 + b[0];}s = s * 256;if (b[1] >= 0) {s = s + b[1];} else {s = s + 256 + b[1];}short result = (short)s;return result;
} /*** 低字節(jié)數(shù)組到short的轉(zhuǎn)換* @param b byte[]* @return short*/
public static short lBytesToShort(byte[] b) {int s = 0;if (b[1] >= 0) {s = s + b[1];} else {s = s + 256 + b[1];}s = s * 256;if (b[0] >= 0) {s = s + b[0];} else {s = s + 256 + b[0];}short result = (short)s;return result;
} /*** 高字節(jié)數(shù)組轉(zhuǎn)換為float* @param b byte[]* @return float*/
public static float hBytesToFloat(byte[] b) {int i = 0;Float F = new Float(0.0);i = ((((b[0]&0xff)<<8 | (b[1]&0xff))<<8) | (b[2]&0xff))<<8 | (b[3]&0xff);return F.intBitsToFloat(i);
} /*** 低字節(jié)數(shù)組轉(zhuǎn)換為float* @param b byte[]* @return float*/
public static float lBytesToFloat(byte[] b) {int i = 0;Float F = new Float(0.0);i = ((((b[3]&0xff)<<8 | (b[2]&0xff))<<8) | (b[1]&0xff))<<8 | (b[0]&0xff);return F.intBitsToFloat(i);
} /*** 將byte數(shù)組中的元素倒序排列*/
public static byte[] bytesReverseOrder(byte[] b) {int length = b.length;byte[] result = new byte[length];for(int i=0; i<length; i++) {result[length-i-1] = b;}return result;
} /*** 打印byte數(shù)組*/
public static void printBytes(byte[] bb) {int length = bb.length;for (int i=0; i<length; i++) {System.out.print(bb + " ");}System.out.println("");
} public static void logBytes(byte[] bb) {int length = bb.length;String out = "";for (int i=0; i<length; i++) {out = out + bb + " ";} } /*** 將int類型的值轉(zhuǎn)換為字節(jié)序顛倒過來對應(yīng)的int值* @param i int* @return int*/
public static int reverseInt(int i) {int result = FormatTransfer.hBytesToInt(FormatTransfer.toLH(i));return result;
} /*** 將short類型的值轉(zhuǎn)換為字節(jié)序顛倒過來對應(yīng)的short值* @param s short* @return short*/
public static short reverseShort(short s) {short result = FormatTransfer.hBytesToShort(FormatTransfer.toLH(s));return result;
} /*** 將float類型的值轉(zhuǎn)換為字節(jié)序顛倒過來對應(yīng)的float值* @param f float* @return float*/
public static float reverseFloat(float f) {float result = FormatTransfer.hBytesToFloat(FormatTransfer.toLH(f));return result;
} }
?
java整型數(shù)與網(wǎng)絡(luò)字節(jié)序的 byte[] 數(shù)組轉(zhuǎn)換關(guān)系
http://www.cnblogs.com/devinzhang/archive/2012/09/28/2707605.html
工作項(xiàng)目需要在java和c/c++之間進(jìn)行socket通信,socket通信是以字節(jié)流或者字節(jié)包進(jìn)行的,socket發(fā)送方須將數(shù)據(jù)轉(zhuǎn)換為字節(jié)流或者字節(jié)包,而接收方則將字節(jié)流和字節(jié)包再轉(zhuǎn)換回相應(yīng)的數(shù)據(jù)類型。如果發(fā)送方和接收方都是同種語言,則一般只涉及到字節(jié)序的調(diào)整。而對于java和c/c++的通信,則情況就要復(fù)雜一些,主要是因?yàn)閖ava中沒有unsigned類型,并且java和c在某些數(shù)據(jù)類型上的長度不一致。
本文就是針對這種情況,整理了java數(shù)據(jù)類型和網(wǎng)絡(luò)字節(jié)流或字節(jié)包(相當(dāng)于java的byte數(shù)組)之間轉(zhuǎn)換方法。實(shí)際上網(wǎng)上這方面的資料不少,但往往不全,甚至有些有錯誤,于是就花了點(diǎn)時間對java整型數(shù)和網(wǎng)絡(luò)字節(jié)序的byte[]之間轉(zhuǎn)換的各種情況做了一些驗(yàn)證和整理。整理出來的函數(shù)如下:
public class ByteConvert {// 以下 是整型數(shù) 和 網(wǎng)絡(luò)字節(jié)序的 byte[] 數(shù)組之間的轉(zhuǎn)換public static byte[] longToBytes(long n) {byte[] b = new byte[8];b[7] = (byte) (n & 0xff);b[6] = (byte) (n >> 8 & 0xff);b[5] = (byte) (n >> 16 & 0xff);b[4] = (byte) (n >> 24 & 0xff);b[3] = (byte) (n >> 32 & 0xff);b[2] = (byte) (n >> 40 & 0xff);b[1] = (byte) (n >> 48 & 0xff);b[0] = (byte) (n >> 56 & 0xff);return b;}public static void longToBytes( long n, byte[] array, int offset ){array[7+offset] = (byte) (n & 0xff);array[6+offset] = (byte) (n >> 8 & 0xff);array[5+offset] = (byte) (n >> 16 & 0xff);array[4+offset] = (byte) (n >> 24 & 0xff);array[3+offset] = (byte) (n >> 32 & 0xff);array[2+offset] = (byte) (n >> 40 & 0xff);array[1+offset] = (byte) (n >> 48 & 0xff);array[0+offset] = (byte) (n >> 56 & 0xff);}public static long bytesToLong( byte[] array ){return ((((long) array[ 0] & 0xff) << 56)| (((long) array[ 1] & 0xff) << 48)| (((long) array[ 2] & 0xff) << 40)| (((long) array[ 3] & 0xff) << 32)| (((long) array[ 4] & 0xff) << 24)| (((long) array[ 5] & 0xff) << 16)| (((long) array[ 6] & 0xff) << 8) | (((long) array[ 7] & 0xff) << 0)); }public static long bytesToLong( byte[] array, int offset ){return ((((long) array[offset + 0] & 0xff) << 56)| (((long) array[offset + 1] & 0xff) << 48)| (((long) array[offset + 2] & 0xff) << 40)| (((long) array[offset + 3] & 0xff) << 32)| (((long) array[offset + 4] & 0xff) << 24)| (((long) array[offset + 5] & 0xff) << 16)| (((long) array[offset + 6] & 0xff) << 8) | (((long) array[offset + 7] & 0xff) << 0)); }public static byte[] intToBytes(int n) {byte[] b = new byte[4];b[3] = (byte) (n & 0xff);b[2] = (byte) (n >> 8 & 0xff);b[1] = (byte) (n >> 16 & 0xff);b[0] = (byte) (n >> 24 & 0xff);return b;}public static void intToBytes( int n, byte[] array, int offset ){array[3+offset] = (byte) (n & 0xff);array[2+offset] = (byte) (n >> 8 & 0xff);array[1+offset] = (byte) (n >> 16 & 0xff);array[offset] = (byte) (n >> 24 & 0xff);} public static int bytesToInt(byte b[]) {return b[3] & 0xff | (b[2] & 0xff) << 8 | (b[1] & 0xff) << 16| (b[0] & 0xff) << 24;}public static int bytesToInt(byte b[], int offset) {return b[offset+3] & 0xff | (b[offset+2] & 0xff) << 8 | (b[offset+1] & 0xff) << 16| (b[offset] & 0xff) << 24;}public static byte[] uintToBytes( long n ){byte[] b = new byte[4];b[3] = (byte) (n & 0xff);b[2] = (byte) (n >> 8 & 0xff);b[1] = (byte) (n >> 16 & 0xff);b[0] = (byte) (n >> 24 & 0xff);return b;}public static void uintToBytes( long n, byte[] array, int offset ){array[3+offset] = (byte) (n );array[2+offset] = (byte) (n >> 8 & 0xff);array[1+offset] = (byte) (n >> 16 & 0xff);array[offset] = (byte) (n >> 24 & 0xff);}public static long bytesToUint(byte[] array) { return ((long) (array[3] & 0xff)) | ((long) (array[2] & 0xff)) << 8 | ((long) (array[1] & 0xff)) << 16 | ((long) (array[0] & 0xff)) << 24; }public static long bytesToUint(byte[] array, int offset) { return ((long) (array[offset+3] & 0xff)) | ((long) (array[offset+2] & 0xff)) << 8 | ((long) (array[offset+1] & 0xff)) << 16 | ((long) (array[offset] & 0xff)) << 24; }public static byte[] shortToBytes(short n) {byte[] b = new byte[2];b[1] = (byte) ( n & 0xff);b[0] = (byte) ((n >> 8) & 0xff);return b;}public static void shortToBytes(short n, byte[] array, int offset ) { array[offset+1] = (byte) ( n & 0xff);array[offset] = (byte) ((n >> 8) & 0xff);}public static short bytesToShort(byte[] b){return (short)( b[1] & 0xff|(b[0] & 0xff) << 8 ); } public static short bytesToShort(byte[] b, int offset){return (short)( b[offset+1] & 0xff|(b[offset] & 0xff) << 8 ); }public static byte[] ushortToBytes(int n) {byte[] b = new byte[2];b[1] = (byte) ( n & 0xff);b[0] = (byte) ((n >> 8) & 0xff);return b;} public static void ushortToBytes(int n, byte[] array, int offset ) {array[offset+1] = (byte) ( n & 0xff);array[offset] = (byte) ((n >> 8) & 0xff);}public static int bytesToUshort(byte b[]) {return b[1] & 0xff | (b[0] & 0xff) << 8;} public static int bytesToUshort(byte b[], int offset) {return b[offset+1] & 0xff | (b[offset] & 0xff) << 8;} public static byte[] ubyteToBytes( int n ){byte[] b = new byte[1];b[0] = (byte) (n & 0xff);return b;}public static void ubyteToBytes( int n, byte[] array, int offset ){array[0] = (byte) (n & 0xff);}public static int bytesToUbyte( byte[] array ){ return array[0] & 0xff;} public static int bytesToUbyte( byte[] array, int offset ){ return array[offset] & 0xff;} // char 類型、 float、double 類型和 byte[] 數(shù)組之間的轉(zhuǎn)換關(guān)系還需繼續(xù)研究實(shí)現(xiàn)。
}測試程序如下:public class ByteConvertTest {public static String byte2Hex(byte[] buf) {StringBuffer strbuf = new StringBuffer();strbuf.append("{");for (byte b : buf) {if (b == 0) {strbuf.append("00");} else if (b == -1) {strbuf.append("FF");} else {String str = Integer.toHexString(b).toUpperCase();// sb.append(a);if (str.length() == 8) {str = str.substring(6, 8);} else if (str.length() < 2) {str = "0" + str;}strbuf.append(str);}strbuf.append(" ");}strbuf.append("}");return strbuf.toString();} public static byte[] longToBytes(long n) {byte[] b = new byte[8];b[7] = (byte) (n & 0xff);b[6] = (byte) (n >> 8 & 0xff);b[5] = (byte) (n >> 16 & 0xff);b[4] = (byte) (n >> 24 & 0xff);b[3] = (byte) (n >> 32 & 0xff);b[2] = (byte) (n >> 40 & 0xff);b[1] = (byte) (n >> 48 & 0xff);b[0] = (byte) (n >> 56 & 0xff);return b;}public static long bytesToLong( byte[] array ){return ((((long) array[ 0] & 0xff) << 56)| (((long) array[ 1] & 0xff) << 48)| (((long) array[ 2] & 0xff) << 40)| (((long) array[ 3] & 0xff) << 32)| (((long) array[ 4] & 0xff) << 24)| (((long) array[ 5] & 0xff) << 16)| (((long) array[ 6] & 0xff) << 8) | (((long) array[ 7] & 0xff) )); }public static int bytesToInt(byte b[]) {return b[3] & 0xff | (b[2] & 0xff) << 8 | (b[1] & 0xff) << 16| (b[0] & 0xff) << 24;}public static long bytesToUint(byte[] array) { return ((long) (array[3] & 0xff)) | ((long) (array[2] & 0xff)) << 8 | ((long) (array[1] & 0xff)) << 16 | ((long) (array[0] & 0xff)) << 24; }public static byte[] uintToBytes( long n ){byte[] b = new byte[4];b[3] = (byte) (n & 0xff);b[2] = (byte) (n >> 8 & 0xff);b[1] = (byte) (n >> 16 & 0xff);b[0] = (byte) (n >> 24 & 0xff);return b;}public static byte[] shortToBytes(short n) {byte[] b = new byte[2];b[1] = (byte) ( n & 0xff);b[0] = (byte) ((n >> 8) & 0xff);return b;}public static short bytesToShort(byte[] b){return (short)( b[1] & 0xff|(b[0] & 0xff) << 8 ); }static void testShortConvert(){System.out.println("=================== short convert =============");System.out.println("byte2Hex(shortToBytes((short)0x11f2))"+byte2Hex(shortToBytes((short)0x11f2))); System.out.print("println 0x11f2:");System.out.println((short)0x11f2); System.out.println("byte2Hex(shortToBytes((short)0xf1f2))"+byte2Hex(shortToBytes((short)0xf1f2))); System.out.print("println 0xf1f2:");System.out.println((short)0xf1f2); System.out.print("println bytesToShort(shortToBytes((short)0x11f2)):");System.out.println((short)bytesToShort(shortToBytes((short)0x11f2))); System.out.print("println bytesToShort(shortToBytes((short)0xf1f2)):");System.out.println((short)bytesToShort(shortToBytes((short)0xf1f2))); }public static byte[] ushortToBytes(int n) {byte[] b = new byte[2];b[1] = (byte) (n & 0xff);b[0] = (byte) (n >> 8 & 0xff);return b;}public static int bytesToUshort(byte b[]) {return b[1] & 0xff | (b[0] & 0xff) << 8;}static void testUshortConvert(){System.out.println("=================== Ushort convert =============");System.out.println("byte2Hex(ushortToBytes(0x11f2))"+byte2Hex(ushortToBytes(0x11f2))); System.out.print("println 0x11f2:");System.out.println(0x11f2); System.out.println("byte2Hex(ushortToBytes(0xf1f2))"+byte2Hex(ushortToBytes(0xf1f2))); System.out.print("println 0xf1f2:");System.out.println(0xf1f2); System.out.print("println bytesToUshort(ushortToBytes(0x11f2)):");System.out.println(bytesToUshort(ushortToBytes(0x11f2))); System.out.print("println bytesToUshort(ushortToBytes(0xf1f2)):");System.out.println(bytesToUshort(ushortToBytes(0xf1f2))); }public static byte[] ubyteToBytes( int n ){byte[] b = new byte[1];b[0] = (byte) (n & 0xff);return b;}public static int bytesToUbyte( byte[] array ){ return array[0] & 0xff;} static void testUbyteConvert(){System.out.println("=================== Ubyte convert =============");System.out.println("byte2Hex(ubyteToBytes(0x1112))"+byte2Hex(ubyteToBytes(0x1112))); System.out.print("println 0x1112:");System.out.println(0x1112); System.out.println("byte2Hex(ubyteToBytes(0xf2))"+byte2Hex(ubyteToBytes(0xf2))); System.out.print("println 0xf2:");System.out.println(0xf2); System.out.print("println bytesToUbyte(ubyteToBytes(0x1112)):");System.out.println(bytesToUbyte(ubyteToBytes(0x1112))); System.out.print("println bytesToUbyte(ubyteToBytes(0xf1f2)):");System.out.println(bytesToUbyte(ubyteToBytes(0xf1f2))); }/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stub byte[] array = new byte[4];array[3] = (byte) 0xF4;array[2] = 0x13;array[1] = 0x12;array[0] = 0x11;System.out.println("=================== Integer bytes =============");System.out.println("the bytes is:"+byte2Hex(array) );System.out.print("println bytesToInt :");System.out.println( bytesToInt(array));System.out.printf("printf bytesToInt :%X\n", bytesToInt(array));System.out.println("=================== long bytes =============");byte[] longBytes = new byte[8];longBytes[7] = (byte) 0xf7;longBytes[6] = (byte) 0x16;longBytes[5] = (byte) 0xf5;longBytes[4] = (byte) 0x14;longBytes[3] = (byte) 0xf3;longBytes[2] = (byte) 0x12;longBytes[1] = (byte) 0xf1;longBytes[0] = (byte) 0x10;System.out.println( "the bytes is:"+byte2Hex(longBytes) );System.out.printf("printf bytesToLong:%X\n",bytesToLong(longBytes));System.out.println("=================byte to long ================");byte b = (byte)0xf1;System.out.print("Println the byte:");System.out.println(b);System.out.printf("Printf the byte:%X\n",b);long l = b;System.out.print("Println byte to long:");System.out.println(l);System.out.printf("printf byte to long:%X\n",l);System.out.println("================= uint Bytes ================");byte[] uint = new byte[4];uint[3] = (byte) 0xf3;uint[2] = (byte) 0x12;uint[1] = (byte) 0xf1;uint[0] = (byte) 0xFF;System.out.println( "the bytes is:"+byte2Hex(uint) );System.out.printf("printf bytesToUint:%X\n",bytesToUint(uint));System.out.print("Println bytesToUint:");System.out.println(bytesToUint(uint));System.out.println("byte2Hex(uintToBytes(0x11f2f3f4f5f6f7f8l)):"+byte2Hex(uintToBytes(0x11f2f3f4f5f6f7f8l)));System.out.println("===============Long Integer=============="); System.out.print("println 0x11f2f3f4f5f6f7f8l:");System.out.println(0x11f2f3f4f5f6f7f8l); System.out.printf("Printf 0x11f2f3f4f5f6f7f8l:%X\n",0x11f2f3f4f5f6f7f8l);System.out.println("println byte2Hex(longToBytes(0x11f2f3f4f5f6f7f8l))"+byte2Hex(longToBytes(0x11f2f3f4f5f6f7f8l)));// 注意,下面的這行,并不能獲得正確的uint。System.out.printf("printf bytesToUint(longToBytes(0x11f2f3f4f5f6f7f8l):%X\n",bytesToUint(longToBytes(0x11f2f3f4f5f6f7f8l)));System.out.println("===============bytesToLong(longToBytes())==============");System.out.println(bytesToLong(longToBytes(0x11f2f3f4f5f6f7f8l)));System.out.printf("%X\n",bytesToLong(longToBytes(0x11f2f3f4f5f6f7f8l)));testShortConvert();testUshortConvert();testUbyteConvert();}}
?
java中int與byte〔4〕的相互轉(zhuǎn)換http://www.cnblogs.com/mayola/archive/2011/11/17/2253101.html我們都知道,JAVA中的基本數(shù)據(jù)類型有int,byte,char,long,float,double...,它們與引用數(shù)據(jù)類型很不一樣,之所有在如此面向?qū)ο蟮腏AVA語言中依然支持這些值類型,就是考慮到性能的原因。現(xiàn)在,同樣是因?yàn)榭紤]到性能,我們需要一種高效的方法使int與byte[]能夠自由的相互轉(zhuǎn)換,理由就是,我們需要在網(wǎng)絡(luò)上傳送數(shù)據(jù),而網(wǎng)絡(luò)上的數(shù)據(jù)都是byte數(shù)據(jù)流,這就需要一個int-> byte[]與byte[] -> int的方法。簡單的方法,我們可以用DataOutputStream與ByteArrayOutputStream來將int轉(zhuǎn)換成byte[],方法就是:int i = 0;ByteArrayOutputStream boutput = newByteArrayOutputStream();DataOutputStream doutput = newDataOutputStream(boutput);doutput.writeInt(i);byte[] buf = boutput.toByteArray();
執(zhí)行相反的過程我們就可以將byte[]->int,我們要用到DataInputStream與ByteArrayInputStream。byte[] buf = new byte[4];ByteArrayInputStream bintput = newByteArrayInputStream(buf);DataInputStream dintput = new DataInputStream();int i = dintput.readInt();上面的方法可以達(dá)到int<->byte[]的轉(zhuǎn)化,下面還有更加高效的方法,雖然看起來會比較費(fèi)勁一些,但是性能的提升是顯而易見的。
?
int -> byte[]privatebyte[] intToByteArray(final int integer) {
int byteNum = (40 -Integer.numberOfLeadingZeros (integer < 0 ? ~integer : integer))/ 8;
byte[] byteArray = new byte[4];for (int n = 0; n < byteNum; n++)
byteArray[3 - n] = (byte) (integer>>> (n * 8));return (byteArray);
}byte[] -> intpublic static int byteArrayToInt(byte[] b, int offset) {int value= 0;for (int i = 0; i < 4; i++) {int shift= (4 - 1 - i) * 8;value +=(b[i + offset] & 0x000000FF) << shift;}return value;}
========================================import java.io.*;public class IOTest {
public static void main(String[] args) throws Exception {int i = 65535; byte[] b = intToByteArray1(i);for(byte bb : b) {System.out.print(bb + " ");}
}public static byte[] intToByteArray1(int i) { byte[] result = new byte[4]; result[0] = (byte)((i >> 24) & 0xFF);result[1] = (byte)((i >> 16) & 0xFF);result[2] = (byte)((i >> 8) & 0xFF); result[3] = (byte)(i & 0xFF);return result;
}public static byte[] intToByteArray2(int i) throws Exception {ByteArrayOutputStream buf = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(buf); out.writeInt(i); byte[] b = buf.toByteArray();out.close();buf.close();return b;
}
?
ByteArrayOutputStream用法
字節(jié)數(shù)組流:
ByteArrayOutputStream: 可以捕獲內(nèi)存緩沖區(qū)的數(shù)據(jù),轉(zhuǎn)換成字節(jié)數(shù)組。
ByteArrayoutputStream bout=new ByteArrayOutputStream();
bout.write(int a); bout.write(int b); bout.write(int c);
byte[] buf=bout.toByteArray();//獲取內(nèi)存緩沖中的數(shù)據(jù)
for(int i=0;i<=buf.length;i++)
{
System.out.println(buf);
}
bout.close();
注:通過調(diào)用reset()方法可以重新定位。
ByteArrayInputStream: 可以將字節(jié)數(shù)組轉(zhuǎn)化為輸入流
ByteArrayInputStream bin=new ByteArrayInputStream(byte[] buf);
int data=0;
while( (b=bin.read())!=-1)
{
System.out.println(b);
}
bin.close();
與DataOutputStream&DataInputStream聯(lián)合使用:
ByteArrayOutputStream bout=new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(bout);
String name="suntao";
int age=19;
dos.writeUTF(name);
dos.writeInt(age);
byte[] buf=bout.toByteArray();//獲取內(nèi)存緩沖區(qū)中的數(shù)據(jù)
dos.close();
bout.close();
ByteArrayInputStream bin=new ByteArrayInputStream(byte[] buf);
DataInputStream dis=new DataInputStream(bin);
String name=dis.readUTF();//從字節(jié)數(shù)組中讀取
int age=dis.readInt();
dis.close();
bin.close();
注: DataInputStream&DataOutputStream還可以與FileInputStream&FileOutputStream
聯(lián)合使用。
其中:
DataInputStream&DataOutputStream關(guān)心如何將數(shù)據(jù)從高層次的形式轉(zhuǎn)化成低層次的形式.
FileInputStream&FileOutputStream關(guān)心如何操作存儲單元以接受和產(chǎn)生數(shù)據(jù)。
?
JAVA里面關(guān)于byte數(shù)組和String之間的轉(zhuǎn)換問題
JAVA里面關(guān)于byte數(shù)組和String之間的轉(zhuǎn)換問題
引自:http://soniccyj.bokee.com/6175850.html
JAVA里面關(guān)于byte數(shù)組和String之間的轉(zhuǎn)換問題
把byte轉(zhuǎn)化成string,必須經(jīng)過編碼。
例如下面一個例子:
import java.io.UnsupportedEncodingException;
public class test{
public static void main(String g[]) {
String s = "12345abcd";
byte b[] = s.getBytes();
String t = b.toString();
System.out.println(t);
}
}
輸出字符串的結(jié)果和字符串s不一樣了.
經(jīng)過以下方式轉(zhuǎn)碼就可以正確轉(zhuǎn)換了:
public class test{
public static void main(String g[]) {
String s = "12345abcd";
byte b[] = s.getBytes();
try {
String t = new String(b);
System.out.print(t);
} catch (Exception e) {
e.printStackTrace();
}
}
}
引自:http://topic.csdn.net/t/20050404/10/3906398.html
String str = "String";
byte[] byte1 = str.getBytes();
String str1 = new String(byte1);
byte[] byte2 = str1.getBytes();
String str2 = new String(byte2);
System.out.println("str<<<" + str);
System.out.println("byte1<<<" + byte1);
System.out.println("str1<<<" + str1);
System.out.println("byte2<<<" + byte2);
System.out.println("str2<<<" + str2);
-------------------------------------
輸出結(jié)果
str<<<String
byte1<<<[B@192d342
str1<<<String
byte2<<<[B@6b97fd
str2<<<String
想請教為什么兩個byte輸出的不一樣呢?
String str = "String";
byte[] byte1 = str.getBytes();
String str1 = new String(byte1);
byte[] byte2 = str1.getBytes();
----------
注意byte1是str得到的byte數(shù)組,而byte2是另一個字符串str1得到的數(shù)組
他們本身也是兩個對象
直接打印實(shí)際上調(diào)用的是toString()方法,而toString()的默認(rèn)實(shí)現(xiàn)是打印對象類型+hashCode()
[B表示byte數(shù)組
@表示之后的是地址
后面跟著的是hashCode,其實(shí)就是其虛擬機(jī)地址
所以這個結(jié)果也就是順理成章了.
最近的項(xiàng)目中要使用到把byte[]類型轉(zhuǎn)換成String字符串然后通過網(wǎng)絡(luò)發(fā)送,但發(fā)現(xiàn)發(fā)現(xiàn)出去的字符串和獲取的字符串雖然是一樣的,但當(dāng)用String的getBytes()的方法得到的byte[]跟原來的byte[]是不一樣的。
看如下代碼:
bytebytes[] = new byte[] { 50, 0, -1, 28, -24 };
String string = new String(bytes);
byte[] ret = string.getBytes();
查看ret的數(shù)據(jù)發(fā)現(xiàn)是50, 0, -17, -65, -67, 28, -17, -65, -67,發(fā)現(xiàn)數(shù)據(jù)并不是原來的數(shù)據(jù)。
而使用如下代碼就可以得到原來的數(shù)據(jù):
bytebytes[] = new byte[] { 50, 0, -1, 28, -24 };
StringisoString = new String(bytes, "ISO-8859-1");
byte[] isoret = isoString.getBytes("ISO-8859-1");
這是為什么呢?原因是第一種方法默認(rèn)是用UTF-8編碼來生成String的,用System.getProperty("sun.jnu.encoding")可以得到Android默認(rèn)編碼是UTF-8。UTF-8是可變長度的編碼,原來的字節(jié)數(shù)組就被改變了。而ISO8859-1通常叫做Latin-1,Latin-1包括了書寫所有西方歐洲語言不可缺少的附加字符,其中 0~127的字符與ASCII碼相同,它是單字節(jié)的編碼方式,這樣第二種方式生成的String里的字節(jié)數(shù)組就跟原來的字節(jié)數(shù)組一樣。在new String使用其他編碼如GBK,GB2312的話一樣也會導(dǎo)致字節(jié)數(shù)組發(fā)生變化,因此要想獲取String里單字節(jié)數(shù)組,就應(yīng)該使用iso8859-1編碼。
?
總結(jié)
以上是生活随笔為你收集整理的Java字节序,java整型数与网络字节序 byte[] 数组转换关系(ByteArrayOutputStream用法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。