java基本类型与字节数组互相转换
前情提要
在一些读文件流,或者网络数据传输时,我们直接接触的一定是一串java字节码,
如何高效把基本类型转换成我们的字节数组就是必须要要求的
实现流程思路


int 转 字节数组
public static byte[] int2Bytes(int n) {
//自己数组的长度就是我们的int在内存中占用的大小==
int len = Integer.SIZE/8;##ddd##
byte[] bytes = new byte[len];
for(int i=0; i<len; i++ ) {
//这里特别重要,主要目的是将我们的int数字的高位一次移动到字节数组中==
//大家都知道int总共占用4个字节,转化到这里,就是将int的二进制码分段存储==
//这里有个技巧 n*8 = n<<3
bytes[i] = (byte) (n >> ((len-1-i)<<3));
}
return bytes;
}
short 转字节数组
public static byte[] short2Bytes(short n) {
int len = Short.SIZE/8;
byte[] bytes = new byte[len];
for(int i=0; i<len; i++ ) {
bytes[i] = (byte) (n >>> ((len-1-i)<<3));
}
return bytes;
}
char 转字节数组
public static byte[] char2Bytes(char n) {
int len = Character.SIZE/8;
byte[] bytes = new byte[len];
for(int i=0; i<len; i++ ) {
bytes[i] = (byte) (n >>> ((len-1-i)<<3));
}
return bytes;
}
long 转字节数组
public static byte[] long2Bytes(long n) {
int len = Long.SIZE/8;
byte[] bytes = new byte[len];
for(int i=0; i<len; i++ ) {
bytes[i] = (byte) (n >>> ((len-1-i)<<3));
}
return bytes;
}
字节数组转int
public static int bytes2Int(byte[] bytes) {
int result=0;
int len = bytes.length;
//result = ((bytes[3] & 0xff)) | ((bytes[2] & 0xff) << 8)| ((bytes[1] & 0xff) << 16) | ((bytes[0])<<24);
for(int i= len-1;i>=0; i--){
result |= (i==0 ? bytes[i]:(bytes[i] & 0xff)) << ((len-1-i)<<3);
}
return result;
}
字节数组转short
public static short bytes2Short(byte[] bytes) {
short result=0;
int len = bytes.length;
for(int i=len-1;i>=0; i--){
result |= (short)(i==0 ? bytes[i]:(bytes[i] & 0xff)) << ((len-1-i)<<3);
}
return result;
}
字节数组转char
public static char bytes2Char(byte[] bytes) {
char result=0;
int len = bytes.length;
for(int i=bytes.length-1;i>=0; i--){
result |= (i==0 ? bytes[i]:(bytes[i] & 0xff)) << ((len-1-i)<<3);
}
return result;
}
字节数组转long
public static long bytes2Long(byte[] bytes) {
long result=0;
int len = bytes.length;
for(int i=len-1;i>=0; i--){
result |= (long)(i==0 ? bytes[i]:(bytes[i] & 0xff)) << ((len-1-i)<<3);
}
return result;
}
本文详细介绍了如何在Java中实现基本数据类型如int、short、char和long与字节数组之间的高效转换。这对于处理文件流或网络数据传输时特别有用,能够帮助开发者理解数据在网络中的传输形式。
1万+

被折叠的 条评论
为什么被折叠?



