Advertisement
raffaele181188

Boolean array to Int bridge

Nov 21st, 2011
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. package com.zybnet.utils;
  2.  
  3. /**
  4.  * Store a boolean[] in an int
  5.  * Max length for input array is 24, since 8 bit are used to store
  6.  * the length of the source array
  7.  *
  8.  * @author Raffaele
  9.  */
  10. public class BoolArrayToInt {
  11.     /*
  12.      * 0x000000ff is used to store the source length
  13.      * 0xff000000 is array[0..7]
  14.      * 0x00ff0000 is array[8..15]
  15.      * 0x0000ff00 is array[16..23]
  16.      */
  17.     public static int toInt(boolean[] array) {
  18.         int encoded = 0;
  19.         if (array.length > 24)
  20.             throw new IllegalArgumentException("Source length can't exceed 24: " + array.length + " given");
  21.         int bit = 0x80000000;
  22.         for (boolean b : array) {
  23.             if (b)
  24.                 encoded |= bit;
  25.             bit = bit >>> 1;
  26.         }
  27.         encoded |= array.length;
  28.         return encoded;
  29.     }
  30.    
  31.     public static boolean[] toBoolean(int transport) {
  32.         int length = 0xff & transport;
  33.         boolean[] array = new boolean[length];
  34.         int bit = 0x80000000;
  35.         for (int i = 0; i < length; i++) {
  36.             boolean b = bit == (bit & transport);
  37.             array[i] = b;
  38.             bit = bit >>> 1;
  39.         }
  40.         return array;
  41.     }
  42. }
  43.  
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement