永发信息网

如何把一个byte数组的数字转换成int

答案:3  悬赏:0  手机版
解决时间 2021-03-31 22:05
  • 提问者网友:杀生予夺
  • 2021-03-30 23:18
如何把一个byte数组的数字转换成int
最佳答案
  • 五星知识达人网友:千夜
  • 2021-03-31 00:31
int转byte数组
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转换为int
public static int byteToInt2(byte[] b)
{

int mask=0xff;

int temp=0;

int n=0;

for(int i=0;i
n<<=8;

temp=b[i]&mask;

n|=temp;

}

return n;

}
全部回答
  • 1楼网友:老鼠爱大米
  • 2021-03-31 03:18
int转byte数组
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转换为int
public static int byteToInt2(byte[] b)
{
int mask=0xff;

int temp=0;

int n=0;

for(int i=0;i
n<<=8;

temp=b[i]&mask;

n|=temp;

}

return n;

}
  • 2楼网友:怙棘
  • 2021-03-31 01:46
这里简单记录下两种转换方式:
第一种:
1、int与byte[]之间的转换(类似的byte short,long型)
[java] view plain copy 
    
public static byte[] intToBytes( int value )   
{   
    byte[] src = new byte[4];  
    src[3] =  (byte) ((value>>24) & 0xFF);  
    src[2] =  (byte) ((value>>16) & 0xFF);  
    src[1] =  (byte) ((value>>8) & 0xFF);    
    src[0] =  (byte) (value & 0xFF);                  
    return src;   
}  
     
public static byte[] intToBytes2(int value)   
{   
    byte[] src = new byte[4];  
    src[0] = (byte) ((value>>24) & 0xFF);  
    src[1] = (byte) ((value>>16)& 0xFF);  
    src[2] = (byte) ((value>>8)&0xFF);    
    src[3] = (byte) (value & 0xFF);       
    return src;  
}  
byte[]转int
[java] view plain copy 
    
public static int bytesToInt(byte[] src, int offset) {  
    int value;    
    value = (int) ((src[offset] & 0xFF)   
            | ((src[offset+1] & 0xFF)<<8)   
            | ((src[offset+2] & 0xFF)<<16)   
            | ((src[offset+3] & 0xFF)<<24));  
    return value;  
}  
  
   
public static int bytesToInt2(byte[] src, int offset) {  
    int value;    
    value = (int) ( ((src[offset] & 0xFF)<<24)  
            |((src[offset+1] & 0xFF)<<16)  
            |((src[offset+2] & 0xFF)<<8)  
            |(src[offset+3] & 0xFF));  
    return value;  
}  
第二种:1、int与byte[]之间的转换(类似的byte
 short,long型)
[java] view plain copy 
     
public static byte[] intToBytes(int value)   
{   
    byte[] byte_src = new byte[4];  
    byte_src[3] = (byte) ((value & 0xFF000000)>>24);  
    byte_src[2] = (byte) ((value & 0x00FF0000)>>16);  
    byte_src[1] = (byte) ((value & 0x0000FF00)>>8);    
    byte_src[0] = (byte) ((value & 0x000000FF));          
    return byte_src;  
}  
byte[]转int
[java] view plain copy 
     
public static int bytesToInt(byte[] ary, int offset) {  
    int value;    
    value = (int) ((ary[offset]&0xFF)   
            | ((ary[offset+1]<<8) & 0xFF00)  
            | ((ary[offset+2]<<16)& 0xFF0000)   
            | ((ary[offset+3]<<24) & 0xFF000000));  
    return value;  
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯