int与byte互相转换,1个int存储4个byte

来源:互联网 发布:sony 淘宝店推荐 编辑:程序博客网 时间:2024/06/05 17:49
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;}}
控制台输出:616263646162636461 62 63 64 

原创粉丝点击