/**
* 通信格式转换
*
* Java和一些windows编程语言如c、c++、delphi所写的网络程序进行通讯时,需要进行相应的转换
* 高、低字节之间的转换
* windows的字节序为低字节开头
* linux,unix的字节序为高字节开头
* java则无论平台变化,都是高字节开头
*/
publicclassFormatTransfer {
/**
* 将int转为低字节在前,高字节在后的byte数组
* @param n int
* @return byte[]
*/
publicstaticbyte[] toLH(intn) {
byte[] b =newbyte[4];
b[0] = (byte) (n &0xff);
b[1] = (byte) (n >>8&0xff);
b[2] = (byte) (n >>16&0xff);
b[3] = (byte) (n >>24&0xff);
returnb;
}
/**
* 将int转为高字节在前,低字节在后的byte数组
* @param n int
* @return byte[]
*/
publicstaticbyte[] toHH(intn) {
byte[] b =newbyte[4];
b[3] = (byte) (n &0xff);
b[2] = (byte) (n >>8&0xff);
b[1] = (byte) (n >>16&0xff);
b[0] = (byte) (n >>24&0xff);
returnb;
}
/**
* 将short转为低字节在前,高字节在后的byte数组
* @param n short
* @return byte[]
*/
publicstaticbyte[] toLH(shortn) {
byte[] b =newbyte[2];
b[0] = (byte) (n &0xff);
b[1] = (byte) (n >>8&0xff);
returnb;
}
/**
* 将short转为高字节在前,低字节在后的byte数组
* @param n short
* @return byte[]
*/
publicstaticbyte[] toHH(shortn) {
byte[] b =newbyte[2];
b[1] = (byte) (n &0xff);
b[0] = (byte) (n >>8&0xff);
returnb;
}
/**
* 将将int转为高字节在前,低字节在后的byte数组
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转为低字节在前,高字节在后的byte数组
*/
publicstaticbyte[] toLH(floatf) {
returntoLH(Float.floatToRawIntBits(f));
}
/**
* 将float转为高字节在前,低字节在后的byte数组
*/
publicstaticbyte[] toHH(floatf) {
returntoHH(Float.floatToRawIntBits(f));
}
/**
* 将String转为byte数组
*/
publicstaticbyte[] stringToBytes(String s,intlength) {
while(s.getBytes().length <>
s += ' ';
}
returns.getBytes();
}
/**
* 将字节数组转换为String
* @param b byte[]
* @return String
*/
publicstaticString bytesToString(byte[] b) {
StringBuffer result = newStringBuffer('');
intlength = b.length;
for(inti=0; i<>
result.append((char)(b &0xff));
}
returnresult.toString();
}
/**
* 将字符串转换为byte数组
* @param s String
* @return byte[]
*/
publicstaticbyte[] stringToBytes(String s) {
returns.getBytes();
}
/**
* 将高字节数组转换为int
* @param b byte[]
* @return int
*/
publicstaticinthBytesToInt(byte[] b) {
ints =0;
for(inti =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];
}
returns;
}
/**
* 将低字节数组转换为int
* @param b byte[]
* @return int
*/
publicstaticintlBytesToInt(byte[] b) {
ints =0;
for(inti =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];
}
returns;
}
/**
* 高字节数组到short的转换
* @param b byte[]
* @return short
*/
publicstaticshorthBytesToShort(byte[] b) {
ints =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];
}
shortresult = (short)s;
returnresult;
}
/**
* 低字节数组到short的转换
* @param b byte[]
* @return short
*/
publicstaticshortlBytesToShort(byte[] b) {
ints =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];
}
shortresult = (short)s;
returnresult;
}
/**
* 高字节数组转换为float
* @param b byte[]
* @return float
*/
publicstaticfloathBytesToFloat(byte[] b) {
inti =0;
Float F = newFloat(0.0);
i = ((((b[0]&0xff)8| (b[1]&0xff))8) | (b[2]&0xff))8| (b[3]&0xff);
returnF.intBitsToFloat(i);
}
/**
* 低字节数组转换为float
* @param b byte[]
* @return float
*/
publicstaticfloatlBytesToFloat(byte[] b) {
inti =0;
Float F = newFloat(0.0);
i = ((((b[3]&0xff)8| (b[2]&0xff))8) | (b[1]&0xff))8| (b[0]&0xff);
returnF.intBitsToFloat(i);
}
/**
* 将byte数组中的元素倒序排列
*/
publicstaticbyte[] bytesReverseOrder(byte[] b) {
intlength = b.length;
byte[] result =newbyte[length];
for(inti=0; i<>
result[length-i-1] = b;
}
returnresult;
}
/**
* 打印byte数组
*/
publicstaticvoidprintBytes(byte[] bb) {
intlength = bb.length;
for(inti=0; i<>
System.out.print(bb + ' ');
}
System.out.println('');
}
publicstaticvoidlogBytes(byte[] bb) {
intlength = bb.length;
String out = '';
for(inti=0; i<>
out = out + bb + ' ';
}
}
/**
* 将int类型的值转换为字节序颠倒过来对应的int值
* @param i int
* @return int
*/
publicstaticintreverseInt(inti) {
intresult = FormatTransfer.hBytesToInt(FormatTransfer.toLH(i));
returnresult;
}
/**
* 将short类型的值转换为字节序颠倒过来对应的short值
* @param s short
* @return short
*/
publicstaticshortreverseShort(shorts) {
shortresult = FormatTransfer.hBytesToShort(FormatTransfer.toLH(s));
returnresult;
}
/**
* 将float类型的值转换为字节序颠倒过来对应的float值
* @param f float
* @return float
*/
publicstaticfloatreverseFloat(floatf) {
floatresult = FormatTransfer.hBytesToFloat(FormatTransfer.toLH(f));
returnresult;
}
}
java整型数与网络字节序的 byte[] 数组转换关系
工作项目需要在java和c/c++之间进行socket通信,socket通信是以字节流或者字节包进行的,socket发送方须将数据转换为字节流或者字节包,而接收方则将字节流和字节包再转换回相应的数据类型。如果发送方和接收方都是同种语言,则一般只涉及到字节序的调整。而对于java和c/c++的通信,则情况就要复杂一些,主要是因为java中没有unsigned类型,并且java和c在某些数据类型上的长度不一致。
本文就是针对这种情况,整理了java数据类型和网络字节流或字节包(相当于java的byte数组)之间转换方法。实际上网上这方面的资料不少,但往往不全,甚至有些有错误,于是就花了点时间对java整型数和网络字节序的byte[]之间转换的各种情况做了一些验证和整理。整理出来的函数如下:
publicclassByteConvert {
// 以下 是整型数 和 网络字节序的 byte[] 数组之间的转换
publicstaticbyte[] longToBytes(longn) {
byte[] b =newbyte[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);
returnb;
}
publicstaticvoidlongToBytes(longn,byte[] array,intoffset ){
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);
}
publicstaticlongbytesToLong(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));
}
publicstaticlongbytesToLong(byte[] array,intoffset )
{
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));
}
publicstaticbyte[] intToBytes(intn) {
byte[] b =newbyte[4];
b[3] = (byte) (n &0xff);
b[2] = (byte) (n >>8&0xff);
b[1] = (byte) (n >>16&0xff);
b[0] = (byte) (n >>24&0xff);
returnb;
}
publicstaticvoidintToBytes(intn,byte[] array,intoffset ){
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);
}
publicstaticintbytesToInt(byteb[]) {
returnb[3] &0xff
| (b[2] &0xff) <>8
| (b[1] &0xff) <>16
| (b[0] &0xff) <>24;
}
publicstaticintbytesToInt(byteb[],intoffset) {
returnb[offset+3] &0xff
| (b[offset+2] &0xff) <>8
| (b[offset+1] &0xff) <>16
| (b[offset] & 0xff) <>24;
}
publicstaticbyte[] uintToBytes(longn )
{
byte[] b =newbyte[4];
b[3] = (byte) (n &0xff);
b[2] = (byte) (n >>8&0xff);
b[1] = (byte) (n >>16&0xff);
b[0] = (byte) (n >>24&0xff);
returnb;
}
publicstaticvoiduintToBytes(longn,byte[] array,intoffset ){
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);
}
publicstaticlongbytesToUint(byte[] array) {
return((long) (array[3] &0xff))
| ((long) (array[2] &0xff)) <>8
| ((long) (array[1] &0xff)) <>16
| ((long) (array[0] &0xff)) <>24;
}
publicstaticlongbytesToUint(byte[] array,intoffset) {
return((long) (array[offset+3] &0xff))
| ((long) (array[offset+2] &0xff)) <>8
| ((long) (array[offset+1] &0xff)) <>16
| ((long) (array[offset] &0xff)) <>24;
}
publicstaticbyte[] shortToBytes(shortn) {
byte[] b =newbyte[2];
b[1] = (byte) ( n &0xff);
b[0] = (byte) ((n >>8) &0xff);
returnb;
}
publicstaticvoidshortToBytes(shortn,byte[] array,intoffset ) {
array[offset+1] = (byte) ( n &0xff);
array[offset] = (byte) ((n >>8) &0xff);
}
publicstaticshortbytesToShort(byte[] b){
return(short)( b[1] &0xff
|(b[0] &0xff) <>8);
}
publicstaticshortbytesToShort(byte[] b,intoffset){
return(short)( b[offset+1] &0xff
|(b[offset] & 0xff) <>8);
}
publicstaticbyte[] ushortToBytes(intn) {
byte[] b =newbyte[2];
b[1] = (byte) ( n &0xff);
b[0] = (byte) ((n >>8) &0xff);
returnb;
}
publicstaticvoidushortToBytes(intn,byte[] array,intoffset ) {
array[offset+1] = (byte) ( n &0xff);
array[offset] = (byte) ((n >>8) &0xff);
}
publicstaticintbytesToUshort(byteb[]) {
returnb[1] &0xff
| (b[0] &0xff) <>8;
}
publicstaticintbytesToUshort(byteb[],intoffset) {
returnb[offset+1] &0xff
| (b[offset] & 0xff) <>8;
}
publicstaticbyte[] ubyteToBytes(intn ){
byte[] b =newbyte[1];
b[0] = (byte) (n &0xff);
returnb;
}
publicstaticvoidubyteToBytes(intn,byte[] array,intoffset ){
array[0] = (byte) (n &0xff);
}
publicstaticintbytesToUbyte(byte[] array ){
returnarray[0] &0xff;
}
publicstaticintbytesToUbyte(byte[] array,intoffset ){
returnarray[offset] &0xff;
}
// char 类型、 float、double 类型和 byte[] 数组之间的转换关系还需继续研究实现。
}
测试程序如下:
publicclassByteConvertTest {
publicstaticString byte2Hex(byte[] buf)
{
StringBuffer strbuf = newStringBuffer();
strbuf.append('{');
for(byteb : buf)
{
if(b ==0)
{
strbuf.append('00');
}
elseif(b == -1)
{
strbuf.append('FF');
}
else
{
String str = Integer.toHexString(b).toUpperCase();
// sb.append(a);
if(str.length() ==8)
{
str = str.substring(6,8);
}
elseif(str.length() <>2)
{
str = '0'+ str;
}
strbuf.append(str);
}
strbuf.append(' ');
}
strbuf.append('}');
returnstrbuf.toString();
}
publicstaticbyte[] longToBytes(longn) {
byte[] b =newbyte[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);
returnb;
}
publicstaticlongbytesToLong(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) ));
}
publicstaticintbytesToInt(byteb[]) {
returnb[3] &0xff
| (b[2] &0xff) <>8
| (b[1] &0xff) <>16
| (b[0] &0xff) <>24;
}
publicstaticlongbytesToUint(byte[] array) {
return((long) (array[3] &0xff))
| ((long) (array[2] &0xff)) <>8
| ((long) (array[1] &0xff)) <>16
| ((long) (array[0] &0xff)) <>24;
}
publicstaticbyte[] uintToBytes(longn )
{
byte[] b =newbyte[4];
b[3] = (byte) (n &0xff);
b[2] = (byte) (n >>8&0xff);
b[1] = (byte) (n >>16&0xff);
b[0] = (byte) (n >>24&0xff);
returnb;
}
publicstaticbyte[] shortToBytes(shortn) {
byte[] b =newbyte[2];
b[1] = (byte) ( n &0xff);
b[0] = (byte) ((n >>8) &0xff);
returnb;
}
publicstaticshortbytesToShort(byte[] b){
return(short)( b[1] &0xff
|(b[0] &0xff) <>8);
}
staticvoidtestShortConvert(){
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)));
}
publicstaticbyte[] ushortToBytes(intn) {
byte[] b =newbyte[2];
b[1] = (byte) (n &0xff);
b[0] = (byte) (n >>8&0xff);
returnb;
}
publicstaticintbytesToUshort(byteb[]) {
returnb[1] &0xff
| (b[0] &0xff) <>8;
}
staticvoidtestUshortConvert(){
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)));
}
publicstaticbyte[] ubyteToBytes(intn ){
byte[] b =newbyte[1];
b[0] = (byte) (n &0xff);
returnb;
}
publicstaticintbytesToUbyte(byte[] array ){
returnarray[0] &0xff;
}
staticvoidtestUbyteConvert(){
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
*/
publicstaticvoidmain(String[] args) {
// TODO Auto-generated method stub
byte[] array =newbyte[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 =newbyte[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 ================');
byteb = (byte)0xf1;
System.out.print('Println the byte:');
System.out.println(b);
System.out.printf('Printf the byte:%X\n',b);
longl = 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 =newbyte[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,char,long,float,double...,它们与引用数据类型很不一样,之所有在如此面向对象的JAVA语言中依然支持这些值类型,就是考虑到性能的原因。现在,同样是因为考虑到性能,我们需要一种高效的方法使int与byte[]能够自由的相互转换,理由就是,我们需要在网络上传送数据,而网络上的数据都是byte数据流,这就需要一个int-> byte[]与byte[] -> int的方法。
简单的方法,我们可以用DataOutputStream与ByteArrayOutputStream来将int转换成byte[],方法就是:
int i = 0;
ByteArrayOutputStream boutput = newByteArrayOutputStream();
DataOutputStream doutput = newDataOutputStream(boutput);
doutput.writeInt(i);
byte[] buf = boutput.toByteArray();
执行相反的过程我们就可以将byte[]->int,我们要用到DataInputStream与ByteArrayInputStream。
byte[] buf = new byte[4];
ByteArrayInputStream bintput = newByteArrayInputStream(buf);
DataInputStream dintput = new DataInputStream();
int i = dintput.readInt();
上面的方法可以达到intbyte[]的转化,下面还有更加高效的方法,虽然看起来会比较费劲一些,但是性能的提升是显而易见的。
int->byte[]
privatebyte[] intToByteArray(finalintinteger) {
intbyteNum = (40-Integer.numberOfLeadingZeros (integer <>0? ~integer : integer))/8;
byte[] byteArray =newbyte[4];
for(intn =0; n <>
byteArray[3- n] = (byte) (integer>>> (n *8));
return(byteArray);
}
byte[] ->int
publicstaticintbyteArrayToInt(byte[] b,intoffset) {
intvalue=0;
for(inti =0; i <>4; i++) {
intshift= (4-1- i) *8;
value +=(b[i + offset] & 0x000000FF) <>
}
returnvalue;
}
========================================
importjava.io.*;
publicclassIOTest {
publicstaticvoidmain(String[] args)throwsException {
inti =65535;
byte[] b = intToByteArray1(i);
for(bytebb : b) {
System.out.print(bb + ' ');
}
}
publicstaticbyte[] intToByteArray1(inti) {
byte[] result =newbyte[4];
result[0] = (byte)((i >>24) &0xFF);
result[1] = (byte)((i >>16) &0xFF);
result[2] = (byte)((i >>8) &0xFF);
result[3] = (byte)(i &0xFF);
returnresult;
}
publicstaticbyte[] intToByteArray2(inti)throwsException {
ByteArrayOutputStream buf = newByteArrayOutputStream();
DataOutputStream out = newDataOutputStream(buf);
out.writeInt(i);
byte[] b = buf.toByteArray();
out.close();
buf.close();
returnb;
}
字节数组流:
ByteArrayOutputStream: 可以捕获内存缓冲区的数据,转换成字节数组。
ByteArrayoutputStream bout=new ByteArrayOutputStream();
bout.write(int a); bout.write(int b); bout.write(int c);
byte[] buf=bout.toByteArray();//获取内存缓冲中的数据
for(int i=0;i<>
{
System.out.println(buf);
}
bout.close();
注:通过调用reset()方法可以重新定位。
ByteArrayInputStream: 可以将字节数组转化为输入流
ByteArrayInputStream bin=new ByteArrayInputStream(byte[] buf);
int data=0;
while( (b=bin.read())!=-1)
{
System.out.println(b);
}
bin.close();
与DataOutputStream&DataInputStream联合使用:
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();//获取内存缓冲区中的数据
dos.close();
bout.close();
ByteArrayInputStream bin=new ByteArrayInputStream(byte[] buf);
DataInputStream dis=new DataInputStream(bin);
String name=dis.readUTF();//从字节数组中读取
int age=dis.readInt();
dis.close();
bin.close();
注: DataInputStream&DataOutputStream还可以与FileInputStream&FileOutputStream
联合使用。
其中:
DataInputStream&DataOutputStream关心如何将数据从高层次的形式转化成低层次的形式.
FileInputStream&FileOutputStream关心如何操作存储单元以接受和产生数据。
JAVA里面关于byte数组和String之间的转换问题
JAVA里面关于byte数组和String之间的转换问题
引自:http://soniccyj.bokee.com/6175850.html
JAVA里面关于byte数组和String之间的转换问题
把byte转化成string,必须经过编码。
例如下面一个例子:
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);
}
}
输出字符串的结果和字符串s不一样了.
经过以下方式转码就可以正确转换了:
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
System.out.println('byte1
System.out.println('str1
System.out.println('byte2
System.out.println('str2
-------------------------------------
输出结果
str<>
byte1<>
str1<>
byte2<>
str2<>
想请教为什么两个byte输出的不一样呢?
String str = 'String';
byte[] byte1 = str.getBytes();
String str1 = new String(byte1);
byte[] byte2 = str1.getBytes();
----------
注意byte1是str得到的byte数组,而byte2是另一个字符串str1得到的数组
他们本身也是两个对象
直接打印实际上调用的是toString()方法,而toString()的默认实现是打印对象类型+hashCode()
[B表示byte数组
@表示之后的是地址
后面跟着的是hashCode,其实就是其虚拟机地址
所以这个结果也就是顺理成章了.
最近的项目中要使用到把byte[]类型转换成String字符串然后通过网络发送,但发现发现出去的字符串和获取的字符串虽然是一样的,但当用String的getBytes()的方法得到的byte[]跟原来的byte[]是不一样的。
看如下代码:
bytebytes[] = new byte[] { 50, 0, -1, 28, -24 };
String string = new String(bytes);
byte[] ret = string.getBytes();
查看ret的数据发现是50, 0, -17, -65, -67, 28, -17, -65, -67,发现数据并不是原来的数据。
而使用如下代码就可以得到原来的数据:
bytebytes[] = new byte[] { 50, 0, -1, 28, -24 };
StringisoString = new String(bytes, 'ISO-8859-1');
byte[] isoret = isoString.getBytes('ISO-8859-1');
这是为什么呢?原因是第一种方法默认是用UTF-8编码来生成String的,用System.getProperty('sun.jnu.encoding')可以得到Android默认编码是UTF-8。UTF-8是可变长度的编码,原来的字节数组就被改变了。而ISO8859-1通常叫做Latin-1,Latin-1包括了书写所有西方欧洲语言不可缺少的附加字符,其中 0~127的字符与ASCII码相同,它是单字节的编码方式,这样第二种方式生成的String里的字节数组就跟原来的字节数组一样。在new String使用其他编码如GBK,GB2312的话一样也会导致字节数组发生变化,因此要想获取String里单字节数组,就应该使用iso8859-1编码。