Java 如何将一个四字节转换为一个整数?以及反过来?

如题所述

第1个回答  推荐于2018-04-12
byte[] b = {3,2,1,9};
String s = new String(b,"UTF8");现将4字节转为一个String s
Integer.parseInt(s),将String转为Integer num,
String.valueOf(num), 将Integer num 转为String

string 转 byte[]
byte[] b= s.getBytes("UTF8");本回答被网友采纳
第2个回答  2013-11-09
byte bytes []= {22, 22, 22, 22};

int a = bytes[0]<<24+bytes[1]<<16+bytes[2]<<8+bytes[3];

byte bytes2[]=new byte[4];
bytes[0]=(byte)(a>>24);
bytes[1]=(byte)((a>>16)&0xff);
bytes[2]=(byte)((a>>8)&0xff);
bytes[3]=(byte)(a&0xff);

上面是例子,避免一下溢出就行了
第3个回答  2013-11-09
你用什么东西存的这四个字节,四个字节摆在一起,就是个整数,你的意思应该是转成Integer吧追问

比如“你好”是四个字节吧,我想把它转成Integer,我想要不要先转成二进制再转成Integer

追答

你好不一定是四个字节,UTF-8编码的话,这是6个字节,你这么转换没什么意思,如果是byte[]转成Integer就按楼下的的方法

本回答被提问者采纳
相似回答