1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| package test;
import sun.misc.Unsafe;
import java.lang.reflect.Field; import java.nio.ByteBuffer;
public class FastBytesToInts { public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { String s = "abcdEFG"; byte[] bs = s.getBytes(); System.out.println("length=" + bs.length); printf(bs); int[] is = new int[2]; Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); Unsafe unsafe = (Unsafe) field.get(null); unsafe.copyMemory(bs, Unsafe.ARRAY_BYTE_BASE_OFFSET, is, Unsafe.ARRAY_INT_BASE_OFFSET + 3, 1); unsafe.copyMemory(bs, Unsafe.ARRAY_BYTE_BASE_OFFSET + 1, is, Unsafe.ARRAY_INT_BASE_OFFSET + 2, 1); unsafe.copyMemory(bs, Unsafe.ARRAY_BYTE_BASE_OFFSET + 2, is, Unsafe.ARRAY_INT_BASE_OFFSET + 1, 1); unsafe.copyMemory(bs, Unsafe.ARRAY_BYTE_BASE_OFFSET + 3, is, Unsafe.ARRAY_INT_BASE_OFFSET, 1); unsafe.copyMemory(bs, Unsafe.ARRAY_BYTE_BASE_OFFSET + 4, is, Unsafe.ARRAY_INT_BASE_OFFSET + 4 + 3, 1); unsafe.copyMemory(bs, Unsafe.ARRAY_BYTE_BASE_OFFSET + 5, is, Unsafe.ARRAY_INT_BASE_OFFSET + 4 + 2, 1); unsafe.copyMemory(bs, Unsafe.ARRAY_BYTE_BASE_OFFSET + 6, is, Unsafe.ARRAY_INT_BASE_OFFSET + 4 + 1, 1); printf(is); System.out.println(intToBits(toInt(new byte[]{bs[0], bs[1], bs[2], bs[3]}))); System.out.println(intToBits(ByteBuffer.wrap(new byte[]{bs[0], bs[1], bs[2], bs[3]}).getInt())); }
public static int toInt(byte[] bs) { return (bs[0] << 24) | ((bs[1] & 0xff) << 16) | ((bs[2] & 0xff) << 8) | (bs[3] & 0xff); }
public static void printf(byte[] bs) { for (byte b : bs) { System.out.print(byteToBits(b)); } System.out.println(); }
public static void printf(int[] is) { for (int i : is) { System.out.print(intToBits(i)); } System.out.println(); }
public static String byteToBits(byte digit) { return toBits(digit, 8); }
public static String intToBits(int digit) { return toBits(digit, 32); }
private static String toBits(int digit, int capacity) { char[] buff = new char[capacity]; for (int i = capacity - 1; i > -1; i--) { buff[i] = (digit & 0x01) > 0 ? '1' : '0'; digit = digit >>> 1; } return new String(buff); } }
|