Created
May 10, 2017 07:38
-
-
Save animeshtrivedi/a4eee4021369e32ca01b7b03d7adf8ac to your computer and use it in GitHub Desktop.
a sample code to unsafe copy from byte[] to double[] (and vice-versa)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void copyTest(String[] args) { | |
Unsafe us = null; | |
try { | |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); | |
f.setAccessible(true); | |
us = (Unsafe) f.get(null); | |
System.err.println(" oh my, I have it : " + us); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
int BYTE_ARRAY_OFFSET = us.arrayBaseOffset(byte[].class); | |
int DOUBLE_ARRAY_OFFSET = us.arrayBaseOffset(double[].class); | |
System.err.println(" Hello w , byte[] " + BYTE_ARRAY_OFFSET + " double [] " + DOUBLE_ARRAY_OFFSET); | |
double[] srcArray = new double[1024]; | |
double[] dstArray = new double[1024]; | |
byte[] byteArray = new byte[1024*8]; | |
Random r = new Random(); | |
int i = 0; | |
for(i=0;i<1024;i++){ | |
srcArray[i] = r.nextDouble(); | |
} | |
us.copyMemory(srcArray, DOUBLE_ARRAY_OFFSET, byteArray, BYTE_ARRAY_OFFSET, 1024*8 ); | |
us.copyMemory(byteArray, BYTE_ARRAY_OFFSET, dstArray, DOUBLE_ARRAY_OFFSET, 1024*8); | |
for(i=0;i<1024;i++) { | |
System.err.println(" src : " + srcArray[i] + " desti " + dstArray[i]); | |
assert (srcArray[i] == dstArray[i]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment