- public class ConvertUtil {
- // bytes[4] to int
- public static int bytesToInt(byte[] intBytes) {
- return (int)( (intBytes[0] & 0xff) << 24) |
- ( (intBytes[1] & 0xff) << 16) |
- ( (intBytes[2] & 0xff) << 8 ) |
- ( (intBytes[3] & 0xff) << 0 ) ;
- }
- // int to bytes[4]
- public static byte[] intToBytes(int i) {
- byte[] intBytes = new byte[4];
- intBytes[0] = (byte) (i >> 24);
- intBytes[1] = (byte) (i >> 16);
- intBytes[2] = (byte) (i >> 8);
- intBytes[3] = (byte) (i >> 0);
- return intBytes;
- }
- public static byte[] longToBytes(long num) {
- byte[] b = new byte[8];
- for (int i = 0; i < 8; i++) {
- b[i] = (byte) (num >>> (56 - i * 8));
- }
- return b;
- }
- public static long bytesToLong(byte[] b) {
- int mask = 0xff;
- long temp = 0;
- long res = 0;
- for (int i = 0; i < 8; i++) {
- res <<= 8;
- temp = b[i] & mask;
- res |= temp;
- }
- return res;
- }
- public static void main(String[] args) {
- // define int i
- int i = 168;
- // int to bytes
- byte[] intBytes = intToBytes(i);
- // bytes to int
- int j = bytesToInt(intBytes);
- // print result
- System.out.println(j);
- long l = 24L;
- byte[] lbytes = longToBytes(l);
- long ls = bytesToLong(lbytes);
- System.out.println("long = " + ls);
- }
- }
int, long和byte[]的互换
最新推荐文章于 2022-07-11 23:35:48 发布