我得到一个整数: 1695609641
当我使用方法时:
String hex = Integer.toHexString(1695609641);
system.out.println(hex);
Run Code Online (Sandbox Code Playgroud)
得到:
6510f329
Run Code Online (Sandbox Code Playgroud)
但我想要一个字节数组:
byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
可能重复:
将整数转换为字节数组(Java)
我需要存储一个缓冲区的长度,在一个4字节大的字节数组中.
伪代码:
private byte[] convertLengthToByte(byte[] myBuffer)
{
int length = myBuffer.length;
byte[] byteLength = new byte[4];
//here is where I need to convert the int length to a byte array
byteLength = length.toByteArray;
return byteLength;
}
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最佳方法是什么?请记住,我必须稍后将该字节数组转换回整数.
我知道Java不允许无符号类型,所以我想知道它如何将整数转换为一个字节.假设我有一个值为255的整数a,我将整数转换为一个字节.值是否以字节11111111表示?换句话说,值是否更多地被视为带符号的8位整数,还是直接复制整数的最后8位?
我正在尝试使用WifiManager和WifiInfo类获取我的手机IP地址.
它返回正确的IP地址反转.
public String getWifiIpAddress() {
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wi = wm.getConnectionInfo();
byte[] ipAddress = BigInteger.valueOf(wi.getIpAddress()).toByteArray();
try {
InetAddress myAddr = InetAddress.getByAddress(ipAddress);
String hostAddr = myAddr.getHostAddress();
return hostAddr;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
Run Code Online (Sandbox Code Playgroud)
结果:73.0.168.192