通過異或運算符號與一個指定的值進行異或運算,從而改變字符串每個字符的值,這樣就可以得到加密后的字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import java.util.Scanner; public class Encypt { public static void main(String args[]){ Scanner scan = new Scanner(System.in); System.out.println( "請輸入一個英文字符串或解密字符串:" ); String password = scan.nextLine(); //獲取用戶輸入 char [] array = password.toCharArray(); //獲取字符數組 for ( int i= 0 ;i<array.length;i++) //遍歷字符數組 { array[i]=( char )(array[i]^ 20000 ); //對每個數組元素進行異或運算 } System.out.println( "加密或解密結果如下:" ); System.out.println( new String(array)); } } |
輸出結果:
1
2
3
4
|
請輸入一個英文字符串或解密字符串: www.sohu.com 加密或解密結果如下: 乗乗乗與乓乏么乕與乃乏乍 |
總結:
位運算可以實現很多高級,高效的運算。比如說加密,乘法中的n次方就是右移n位,速度還快。