1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java byte数组与int long short byte转换

java byte数组与int long short byte转换

时间:2024-02-18 03:03:25

相关推荐

java byte数组与int long short byte转换

1 public class DataTypeChangeHelper { 2/** 3* 将一个单字节的byte转换成32位的int 4* 5* @param b 6* byte 7* @return convert result 8*/ 9public static int unsignedByteToInt(byte b) { 10 return (int) b & 0xFF; 11} 12 13/** 14* 将一个单字节的Byte转换成十六进制的数 15* 16* @param b 17* byte 18* @return convert result 19*/ 20public static String byteToHex(byte b) { 21 int i = b & 0xFF; 22 return Integer.toHexString(i); 23} 24 25/** 26* 将一个4byte的数组转换成32位的int 27* 28* @param buf 29* bytes buffer 30* @param byte[]中开始转换的位置 31* @return convert result 32*/ 33public static long unsigned4BytesToInt(byte[] buf, int pos) { 34 int firstByte = 0; 35 int secondByte = 0; 36 int thirdByte = 0; 37 int fourthByte = 0; 38 int index = pos; 39 firstByte = (0x000000FF & ((int) buf[index])); 40 secondByte = (0x000000FF & ((int) buf[index + 1])); 41 thirdByte = (0x000000FF & ((int) buf[index + 2])); 42 fourthByte = (0x000000FF & ((int) buf[index + 3])); 43 index = index + 4; 44 return ((long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFL; 45} 46 47/** 48* 将16位的short转换成byte数组 49* 50* @param s 51* short 52* @return byte[] 长度为2 53* */ 54public static byte[] shortToByteArray(short s) { 55 byte[] targets = new byte[2]; 56 for (int i = 0; i < 2; i++) { 57 int offset = (targets.length - 1 - i) * 8; 58 targets[i] = (byte) ((s >>> offset) & 0xff); 59 } 60 return targets; 61} 62 63/** 64* 将32位整数转换成长度为4的byte数组 65* 66* @param s 67* int 68* @return byte[] 69* */ 70public static byte[] intToByteArray(int s) { 71 byte[] targets = new byte[2]; 72 for (int i = 0; i < 4; i++) { 73 int offset = (targets.length - 1 - i) * 8; 74 targets[i] = (byte) ((s >>> offset) & 0xff); 75 } 76 return targets; 77} 78 79/** 80* long to byte[] 81* 82* @param s 83* long 84* @return byte[] 85* */ 86public static byte[] longToByteArray(long s) { 87 byte[] targets = new byte[2]; 88 for (int i = 0; i < 8; i++) { 89 int offset = (targets.length - 1 - i) * 8; 90 targets[i] = (byte) ((s >>> offset) & 0xff); 91 } 92 return targets; 93} 94 95/**32位int转byte[]*/ 96public static byte[] int2byte(int res) { 97 byte[] targets = new byte[4]; 98 targets[0] = (byte) (res & 0xff);// 最低位 99 targets[1] = (byte) ((res >> 8) & 0xff);// 次低位100 targets[2] = (byte) ((res >> 16) & 0xff);// 次高位101 targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。102 return targets;103}104 105/**106* 将长度为2的byte数组转换为16位int107* 108* @param res109* byte[]110* @return int111* */112public static int byte2int(byte[] res) {113 // res = InversionByte(res);114 // 一个byte数据左移24位变成0x??000000,再右移8位变成0x00??0000115 int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00); // | 表示安位或116 return targets;117}118 }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。