944,149 Members | Top Members by Rank

Ad:
  • Java Code Snippet
  • Views: 21063
  • Java RSS
1

Primitive types as byte arrays

by on Feb 7th, 2007
Often we're faced with the need to represent primitive data types as readable/writable bytes that can be sent through a data stream. In Java, there are classes such as DataOutputStream/DataInputStream that can do the work for us, but often a programmer wants to manage the conversions himself (or herself, to be politically correct).

So, how does one convert primitive data types to and from [binary] byte arrays? The answer is this: by working with Binary Bitwise Operators.

Here are some methods used to convert primitive types, and arrays of primitive types, to and from byte arrays.

Order of primitive types in this snippet:
  1. byte, byte[]
  2. short, short[]
  3. char, char[]
  4. int, int[]
  5. long, long[]
  6. float, float[]
  7. double, double[]
  8. boolean, boolean[] (special)
  9. String, String[] (special)

I know there are a few formatting mistakes in the code, but hopefully the syntax is all optimal. Perhaps, perhaps not. Something tells me the String conversion isn't UFT safe, too. Any thoughts?
Java Code Snippet (Toggle Plain Text)
  1. /* ========================= */
  2. /* "primitive type --> byte[] data" Methods */
  3. /* ========================= */
  4.  
  5. public static byte[] toByta(byte data) {
  6. return new byte[]{data};
  7. }
  8.  
  9. public static byte[] toByta(byte[] data) {
  10. return data;
  11. }
  12.  
  13. /* ========================= */
  14.  
  15. public static byte[] toByta(short data) {
  16. return new byte[] {
  17. (byte)((data >> 8) & 0xff),
  18. (byte)((data >> 0) & 0xff),
  19. };
  20. }
  21.  
  22. public static byte[] toByta(short[] data) {
  23. if (data == null) return null;
  24. // ----------
  25. byte[] byts = new byte[data.length * 2];
  26. for (int i = 0; i < data.length; i++)
  27. System.arraycopy(toByta(data[i]), 0, byts, i * 2, 2);
  28. return byts;
  29. }
  30.  
  31. /* ========================= */
  32.  
  33. public static byte[] toByta(char data) {
  34. return new byte[] {
  35. (byte)((data >> 8) & 0xff),
  36. (byte)((data >> 0) & 0xff),
  37. };
  38. }
  39.  
  40. public static byte[] toByta(char[] data) {
  41. if (data == null) return null;
  42. // ----------
  43. byte[] byts = new byte[data.length * 2];
  44. for (int i = 0; i < data.length; i++)
  45. System.arraycopy(toByta(data[i]), 0, byts, i * 2, 2);
  46. return byts;
  47. }
  48.  
  49. /* ========================= */
  50.  
  51. public static byte[] toByta(int data) {
  52. return new byte[] {
  53. (byte)((data >> 24) & 0xff),
  54. (byte)((data >> 16) & 0xff),
  55. (byte)((data >> 8) & 0xff),
  56. (byte)((data >> 0) & 0xff),
  57. };
  58. }
  59.  
  60. public static byte[] toByta(int[] data) {
  61. if (data == null) return null;
  62. // ----------
  63. byte[] byts = new byte[data.length * 4];
  64. for (int i = 0; i < data.length; i++)
  65. System.arraycopy(toByta(data[i]), 0, byts, i * 4, 4);
  66. return byts;
  67. }
  68.  
  69. /* ========================= */
  70.  
  71. public static byte[] toByta(long data) {
  72. return new byte[] {
  73. (byte)((data >> 56) & 0xff),
  74. (byte)((data >> 48) & 0xff),
  75. (byte)((data >> 40) & 0xff),
  76. (byte)((data >> 32) & 0xff),
  77. (byte)((data >> 24) & 0xff),
  78. (byte)((data >> 16) & 0xff),
  79. (byte)((data >> 8) & 0xff),
  80. (byte)((data >> 0) & 0xff),
  81. };
  82. }
  83.  
  84. public static byte[] toByta(long[] data) {
  85. if (data == null) return null;
  86. // ----------
  87. byte[] byts = new byte[data.length * 8];
  88. for (int i = 0; i < data.length; i++)
  89. System.arraycopy(toByta(data[i]), 0, byts, i * 8, 8);
  90. return byts;
  91. }
  92.  
  93. /* ========================= */
  94.  
  95. public static byte[] toByta(float data) {
  96. return toByta(Float.floatToRawIntBits(data));
  97. }
  98.  
  99. public static byte[] toByta(float[] data) {
  100. if (data == null) return null;
  101. // ----------
  102. byte[] byts = new byte[data.length * 4];
  103. for (int i = 0; i < data.length; i++)
  104. System.arraycopy(toByta(data[i]), 0, byts, i * 4, 4);
  105. return byts;
  106. }
  107.  
  108. /* ========================= */
  109.  
  110. public static byte[] toByta(double data) {
  111. return toByta(Double.doubleToRawLongBits(data));
  112. }
  113.  
  114. public static byte[] toByta(double[] data) {
  115. if (data == null) return null;
  116. // ----------
  117. byte[] byts = new byte[data.length * 8];
  118. for (int i = 0; i < data.length; i++)
  119. System.arraycopy(toByta(data[i]), 0, byts, i * 8, 8);
  120. return byts;
  121. }
  122.  
  123. /* ========================= */
  124.  
  125. public static byte[] toByta(boolean data) {
  126. return new byte[]{(byte)(data ? 0x01 : 0x00)}; // bool -> {1 byte}
  127. }
  128.  
  129. public static byte[] toByta(boolean[] data) {
  130. // Advanced Technique: The byte array containts information
  131. // about how many boolean values are involved, so the exact
  132. // array is returned when later decoded.
  133. // ----------
  134. if (data == null) return null;
  135. // ----------
  136. int len = data.length;
  137. byte[] lena = toByta(len); // int conversion; length array = lena
  138. byte[] byts = new byte[lena.length + (len / 8) + (len % 8 != 0 ? 1 : 0)];
  139. // (Above) length-array-length + sets-of-8-booleans +? byte-for-remainder
  140. System.arraycopy(lena, 0, byts, 0, lena.length);
  141. // ----------
  142. // (Below) algorithm by Matthew Cudmore: boolean[] -> bits -> byte[]
  143. for (int i = 0, j = lena.length, k = 7; i < data.length; i++) {
  144. byts[j] |= (data[i] ? 1 : 0) << k--;
  145. if (k < 0) { j++; k = 7; }
  146. }
  147. // ----------
  148. return byts;
  149. }
  150.  
  151. /* ========================= */
  152.  
  153. public static byte[] toByta(String data) {
  154. return (data == null) ? null : data.getBytes();
  155. }
  156.  
  157. public static byte[] toByta(String[] data) {
  158. // Advanced Technique: Generates an indexed byte array
  159. // which contains the array of Strings. The byte array
  160. // contains information about the number of Strings and
  161. // the length of each String.
  162. // ----------
  163. if (data == null) return null;
  164. // ---------- flags:
  165. int totalLength = 0; // Measure length of final byte array
  166. int bytesPos = 0; // Used later
  167. // ----- arrays:
  168. byte[] dLen = toByta(data.length); // byte array of data length
  169. totalLength += dLen.length;
  170. int[] sLens = new int[data.length]; // String lengths = sLens
  171. totalLength += (sLens.length * 4);
  172. byte[][] strs = new byte[data.length][]; // array of String bytes
  173. // ----- pack strs:
  174. for (int i = 0; i < data.length; i++) {
  175. if (data[i] != null) {
  176. strs[i] = toByta(data[i]);
  177. sLens[i] = strs[i].length;
  178. totalLength += strs[i].length;
  179. } else {
  180. sLens[i] = 0;
  181. strs[i] = new byte[0]; // prevent null entries
  182. }
  183. }
  184. // ----------
  185. byte[] bytes = new byte[totalLength]; // final array
  186. System.arraycopy(dLen, 0, bytes, 0, 4);
  187. byte[] bsLens = toByta(sLens); // byte version of String sLens
  188. System.arraycopy(bsLens, 0, bytes, 4, bsLens.length);
  189. // -----
  190. bytesPos += 4 + bsLens.length; // mark position
  191. // -----
  192. for (byte[] sba : strs) {
  193. System.arraycopy(sba, 0, bytes, bytesPos, sba.length);
  194. bytesPos += sba.length;
  195. }
  196. // ----------
  197. return bytes;
  198. }
  199.  
  200. /* ========================= */
  201. /* "byte[] data --> primitive type" Methods */
  202. /* ========================= */
  203.  
  204. public static byte toByte(byte[] data) {
  205. return (data == null || data.length == 0) ? 0x0 : data[0];
  206. }
  207.  
  208. public static byte[] toByteA(byte[] data) {
  209. return data;
  210. }
  211.  
  212. /* ========================= */
  213.  
  214. public static short toShort(byte[] data) {
  215. if (data == null || data.length != 2) return 0x0;
  216. // ----------
  217. return (short)(
  218. (0xff & data[0]) << 8 |
  219. (0xff & data[1]) << 0
  220. );
  221. }
  222.  
  223. public static short[] toShortA(byte[] data) {
  224. if (data == null || data.length % 2 != 0) return null;
  225. // ----------
  226. short[] shts = new short[data.length / 2];
  227. for (int i = 0; i < shts.length; i++) {
  228. shts[i] = toShort( new byte[] {
  229. data[(i*2)],
  230. data[(i*2)+1]
  231. } );
  232. }
  233. return shts;
  234. }
  235.  
  236. /* ========================= */
  237.  
  238. public static char toChar(byte[] data) {
  239. if (data == null || data.length != 2) return 0x0;
  240. // ----------
  241. return (char)(
  242. (0xff & data[0]) << 8 |
  243. (0xff & data[1]) << 0
  244. );
  245. }
  246.  
  247. public static char[] toCharA(byte[] data) {
  248. if (data == null || data.length % 2 != 0) return null;
  249. // ----------
  250. char[] chrs = new char[data.length / 2];
  251. for (int i = 0; i < chrs.length; i++) {
  252. chrs[i] = toChar( new byte[] {
  253. data[(i*2)],
  254. data[(i*2)+1],
  255. } );
  256. }
  257. return chrs;
  258. }
  259.  
  260. /* ========================= */
  261.  
  262. public static int toInt(byte[] data) {
  263. if (data == null || data.length != 4) return 0x0;
  264. // ----------
  265. return (int)( // NOTE: type cast not necessary for int
  266. (0xff & data[0]) << 24 |
  267. (0xff & data[1]) << 16 |
  268. (0xff & data[2]) << 8 |
  269. (0xff & data[3]) << 0
  270. );
  271. }
  272.  
  273. public static int[] toIntA(byte[] data) {
  274. if (data == null || data.length % 4 != 0) return null;
  275. // ----------
  276. int[] ints = new int[data.length / 4];
  277. for (int i = 0; i < ints.length; i++)
  278. ints[i] = toInt( new byte[] {
  279. data[(i*4)],
  280. data[(i*4)+1],
  281. data[(i*4)+2],
  282. data[(i*4)+3],
  283. } );
  284. return ints;
  285. }
  286.  
  287. /* ========================= */
  288.  
  289. public static long toLong(byte[] data) {
  290. if (data == null || data.length != 8) return 0x0;
  291. // ----------
  292. return (long)(
  293. // (Below) convert to longs before shift because digits
  294. // are lost with ints beyond the 32-bit limit
  295. (long)(0xff & data[0]) << 56 |
  296. (long)(0xff & data[1]) << 48 |
  297. (long)(0xff & data[2]) << 40 |
  298. (long)(0xff & data[3]) << 32 |
  299. (long)(0xff & data[4]) << 24 |
  300. (long)(0xff & data[5]) << 16 |
  301. (long)(0xff & data[6]) << 8 |
  302. (long)(0xff & data[7]) << 0
  303. );
  304. }
  305.  
  306. public static long[] toLongA(byte[] data) {
  307. if (data == null || data.length % 8 != 0) return null;
  308. // ----------
  309. long[] lngs = new long[data.length / 8];
  310. for (int i = 0; i < lngs.length; i++) {
  311. lngs[i] = toLong( new byte[] {
  312. data[(i*8)],
  313. data[(i*8)+1],
  314. data[(i*8)+2],
  315. data[(i*8)+3],
  316. data[(i*8)+4],
  317. data[(i*8)+5],
  318. data[(i*8)+6],
  319. data[(i*8)+7],
  320. } );
  321. }
  322. return lngs;
  323. }
  324.  
  325. /* ========================= */
  326.  
  327. public static float toFloat(byte[] data) {
  328. if (data == null || data.length != 4) return 0x0;
  329. // ---------- simple:
  330. return Float.intBitsToFloat(toInt(data));
  331. }
  332.  
  333. public static float[] toFloatA(byte[] data) {
  334. if (data == null || data.length % 4 != 0) return null;
  335. // ----------
  336. float[] flts = new float[data.length / 4];
  337. for (int i = 0; i < flts.length; i++) {
  338. flts[i] = toFloat( new byte[] {
  339. data[(i*4)],
  340. data[(i*4)+1],
  341. data[(i*4)+2],
  342. data[(i*4)+3],
  343. } );
  344. }
  345. return flts;
  346. }
  347.  
  348. /* ========================= */
  349.  
  350. public static double toDouble(byte[] data) {
  351. if (data == null || data.length != 8) return 0x0;
  352. // ---------- simple:
  353. return Double.longBitsToDouble(toLong(data));
  354. }
  355.  
  356. public static double[] toDoubleA(byte[] data) {
  357. if (data == null) return null;
  358. // ----------
  359. if (data.length % 8 != 0) return null;
  360. double[] dbls = new double[data.length / 8];
  361. for (int i = 0; i < dbls.length; i++) {
  362. dbls[i] = toDouble( new byte[] {
  363. data[(i*8)],
  364. data[(i*8)+1],
  365. data[(i*8)+2],
  366. data[(i*8)+3],
  367. data[(i*8)+4],
  368. data[(i*8)+5],
  369. data[(i*8)+6],
  370. data[(i*8)+7],
  371. } );
  372. }
  373. return dbls;
  374. }
  375.  
  376. /* ========================= */
  377.  
  378. public static boolean toBoolean(byte[] data) {
  379. return (data == null || data.length == 0) ? false : data[0] != 0x00;
  380. }
  381.  
  382. public static boolean[] toBooleanA(byte[] data) {
  383. // Advanced Technique: Extract the boolean array's length
  384. // from the first four bytes in the char array, and then
  385. // read the boolean array.
  386. // ----------
  387. if (data == null || data.length < 4) return null;
  388. // ----------
  389. int len = toInt(new byte[]{data[0], data[1], data[2], data[3]});
  390. boolean[] bools = new boolean[len];
  391. // ----- pack bools:
  392. for (int i = 0, j = 4, k = 7; i < bools.length; i++) {
  393. bools[i] = ((data[j] >> k--) & 0x01) == 1;
  394. if (k < 0) { j++; k = 7; }
  395. }
  396. // ----------
  397. return bools;
  398. }
  399.  
  400. /* ========================= */
  401.  
  402. public static String toString(byte[] data) {
  403. return (data == null) ? null : new String(data);
  404. }
  405.  
  406. public static String[] toStringA(byte[] data) {
  407. // Advanced Technique: Extract the String array's length
  408. // from the first four bytes in the char array, and then
  409. // read the int array denoting the String lengths, and
  410. // then read the Strings.
  411. // ----------
  412. if (data == null || data.length < 4) return null;
  413. // ----------
  414. byte[] bBuff = new byte[4]; // Buffer
  415. // -----
  416. System.arraycopy(data, 0, bBuff, 0, 4);
  417. int saLen = toInt(bBuff);
  418. if (data.length < (4 + (saLen * 4))) return null;
  419. // -----
  420. bBuff = new byte[saLen * 4];
  421. System.arraycopy(data, 4, bBuff, 0, bBuff.length);
  422. int[] sLens = toIntA(bBuff);
  423. if (sLens == null) return null;
  424. // ----------
  425. String[] strs = new String[saLen];
  426. for (int i = 0, dataPos = 4 + (saLen * 4); i < saLen; i++) {
  427. if (sLens[i] > 0) {
  428. if (data.length >= (dataPos + sLens[i])) {
  429. bBuff = new byte[sLens[i]];
  430. System.arraycopy(data, dataPos, bBuff, 0, sLens[i]);
  431. dataPos += sLens[i];
  432. strs[i] = toString(bBuff);
  433. } else return null;
  434. }
  435. }
  436. // ----------
  437. return strs;
  438. }
Comments on this Code Snippet
Mar 15th, 2010
0

Re: Primitive types as byte arrays

This is great!
Just what I was looking for...
I need to convert an integer to an unsigned integer 2 byte array - how would I do that?

-Steve
Newbie Poster
touw_22 is offline Offline
1 posts
since Mar 2010
Mar 15th, 2010
0

Re: Primitive types as byte arrays

@touw_22 please create new thread and ask there. At the moment you are hijacking someone else post, similar need doesn't mean same.
Code tags enforcer
peter_budo is offline Offline
6,659 posts
since Dec 2004
Message:
Previous Thread in Java Forum Timeline: writing to file trouble, jgrasp! keeps writing over previous text put in
Next Thread in Java Forum Timeline: How to keep the input





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC