java中int与byte〔4〕的相互转换
由于我要进行网络传输,因此我想将int与byte进行转换,一个int占四个字节,所以我请问怎么把int转为byte〔4〕应该是要涉及到位操作吧?...
由于我要进行网络传输,因此我想将int与byte进行转换,一个int占四个字节,所以我请问怎么把int转为byte〔4〕
应该是要涉及到位操作吧? 展开
应该是要涉及到位操作吧? 展开
2个回答
展开全部
import java.io.*;
public class IOTest {
public static void main(String[] args) throws Exception {
int i = 65535;
byte[] b = intToByteArray1(i);
for(byte bb : b) {
System.out.print(bb + " ");
}
}
public static byte[] intToByteArray1(int i) {
byte[] result = new byte[4];
result[0] = (byte)((i >> 24) & 0xFF);
result[1] = (byte)((i >> 16) & 0xFF);
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)(i & 0xFF);
return result;
}
public static byte[] intToByteArray2(int i) throws Exception {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
out.writeInt(i);
byte[] b = buf.toByteArray();
out.close();
buf.close();
return b;
}
}
public class IOTest {
public static void main(String[] args) throws Exception {
int i = 65535;
byte[] b = intToByteArray1(i);
for(byte bb : b) {
System.out.print(bb + " ");
}
}
public static byte[] intToByteArray1(int i) {
byte[] result = new byte[4];
result[0] = (byte)((i >> 24) & 0xFF);
result[1] = (byte)((i >> 16) & 0xFF);
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)(i & 0xFF);
return result;
}
public static byte[] intToByteArray2(int i) throws Exception {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
out.writeInt(i);
byte[] b = buf.toByteArray();
out.close();
buf.close();
return b;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询