简体   繁体   中英

How to convert a string of Text into a string of bits?

I've been attempting to create sort of a One Time Pad encrption in my free time in order to learn a bit. My idea was to convert the input(which shall be encrypted) into a String of bits. Then I have a password (also in a String of bits) and the input gets encrypted with XOR. eg pw= 101001 , input= 11001, then enc= 0110. My problem now is:

how does binary.append((val&128)==0 ? 0 : 1); work? I guess I can rewrite this as

if(val&128)==0{
   binary.append(0);
}else{
   binary.append(1);
}

But how can 2 Numbers ( val&128 ) equal to one number (0) ? This is my code:

String s ="foo";
 byte[] bytes = s.getBytes();
 StringBuilder binary = new StringBuilder();
 for(byte[] b : bytes){
   int val = b;
   for(int i=0; i<8; i++){
       binary.append((val&128)==0 ? 0 : 1);
       val <<= 1;
   }
 }
 System.out.println(s + " to binary: " + binary)

Thanks for help:)

The & operator takes in two integer values and compares them bitwise so it gives you another integer value, which is generated by writing the two int values in binary format among themselves and comparing every bit with the AND operation.

A result is again a binary number which is converted back to a base 10 integer. Therefore you can compare it with the integer 0.

Example :

15 & 7 = 7:
1111 (15) & 0111 (7) = 0111 (7)

Explaination how's binary.append((val&128)==0 ? 0 : 1); working

 for(byte[] b : bytes){
   int val = b;
   for(int i=0; i<8; i++){
       binary.append((val&128)==0 ? 0 : 1);
       val <<= 1;
   }
 }

val contains the value of byte 'b' as integer and every byte has 8 bits thats why loop is running 8 times and every time loop checks that if right most digit 1 or not. If right most bit is 1 then append 1 in string builder (vairable name binary) otherwise 0. and right shift val by 1.

  1. (val&128)==0 ? 0 : 1 ==> checks if right most digit is 1 or not
  2. val<<=1 ==> right shift operation eg val=17 binary of val = 00010001 val<<=1 ==> binary of val = 00100010, val = 34

binary.append((val&128)==0 ? 0 : 1); it appends 1 to binary (StringBuilder) if right most bit is 1 otherwise appends 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM