public class IntOrByte { public static void main(String[] args) { System.out.println(intHexString(byteConvertInt(new byte[]{'a','b','c','d'}))); System.out.println(bytes2HexString(new byte[]{'a','b','c','d'})); for(byte b:intConverByte(byteConvertInt(new byte[]{'a','b','c','d'}))){ System.out.print(intHexString(b)+" "); } } //转换16进制显示 public static String bytes2HexString(byte[] bs) { String ret = ""; for(int i=0;i<bs.length;i++){ String hex = Integer.toHexString(bs[i] & 0xFF ); if (hex.length() == 1) { hex = '0' + hex; } ret += hex.toUpperCase(); } return ret; } //转换16进制显示 public static String intHexString(int bs) { String ret = ""; String hex = Integer.toHexString(bs ); if (hex.length() == 1) { hex = '0' + hex; } ret += hex.toUpperCase(); return ret;
}//byte 转 intpublic static int byteConvertInt(byte[] b) {int pos = 0;int value = 0;for (int i = 0; i < 4; i++) {int shift=(b.length-i-1) * 8;value += (b[pos+i]& 0x000000FF) << shift;}pos += 4;return value;}//int 转 bytepublic static byte[] intConverByte(int in){byte[] b = new byte[4];for (int i = 0; i < 4; i++) { int shift = (b.length - 1 - i) * 8; b[i] = (byte) ((in >> shift) & 0xFF);}return b;}}控制台输出: 61626364 61626364 61 62 63 64
int与byte互相转换,1个int存储4个byte
最新推荐文章于 2023-03-11 09:49:16 发布