Advertisement
mikhail_dvorkin

String to BitSet

Oct 20th, 2017
460
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. import java.util.BitSet;
  2.  
  3. public class HelloWorld {
  4.     public static void main(String[] args) {
  5.         String s = "hello@^@$05oiejfcq3941[u204";
  6.         System.out.println(s);
  7.         BitSet a = stringToBitSet(s);
  8.         System.out.println(a);
  9.         s = bitSetToString(a);
  10.         System.out.println(s);
  11.     }
  12.  
  13.     static String bitSetToString(BitSet a) {
  14.         int length = (a.length() + Character.SIZE - 1)
  15.                 / Character.SIZE;
  16.         char[] result = new char[length];
  17.         for (int i = 0; i < length; i++) {
  18.             BitSet character =
  19.                     a.get(Character.SIZE * i,
  20.                     Character.SIZE * (i + 1));
  21.             result[i] = (char)
  22.                     character.toLongArray()[0];
  23.         }
  24.         return new String(result);
  25.     }
  26.  
  27.     private static BitSet stringToBitSet(String s) {
  28.         BitSet a = new BitSet();
  29.         for (int i = 0; i < s.length(); i++) {
  30.             char c = s.charAt(i);
  31.             for (int j = 0; j < Character.SIZE; j++) {
  32.                 boolean bit = ((c >> j) & 1) > 0;
  33.                 a.set(Character.SIZE * i + j, bit);
  34.             }
  35.         }
  36.         return a;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement