更新時間:2022-12-13 12:05:59 來源:動力節點 瀏覽3003次
將字符串轉換為其二進制格式的步驟。
將字符串轉換為char[].
循環char[].
Integer.toBinaryString(aChar)將字符轉換為二進制字符串。
String.format如果需要創建填充。
package com.mkyong.crypto.bytes;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StringToBinaryExample1 {
public static void main(String[] args) {
String input = "Hello";
String result = convertStringToBinary(input);
System.out.println(result);
// pretty print the binary format
System.out.println(prettyBinary(result, 8, " "));
}
public static String convertStringToBinary(String input) {
StringBuilder result = new StringBuilder();
char[] chars = input.toCharArray();
for (char aChar : chars) {
result.append(
String.format("%8s", Integer.toBinaryString(aChar)) // char -> int, auto-cast
.replaceAll(" ", "0") // zero pads
);
}
return result.toString();
}
public static String prettyBinary(String binary, int blockSize, String separator) {
List<String> result = new ArrayList<>();
int index = 0;
while (index < binary.length()) {
result.add(binary.substring(index, Math.min(index + blockSize, binary.length())));
index += blockSize;
}
return result.stream().collect(Collectors.joining(separator));
}
}
輸出
0100100001100101011011000110110001101111
01001000 01100101 01101100 01101100 01101111
(1)此 Java 示例將使用位掩碼技術從 8 位字節生成二進制格式。
package com.mkyong.crypto.bytes;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StringToBinaryExample2 {
public static void main(String[] args) {
String input = "a";
String result = convertByteArraysToBinary(input.getBytes(StandardCharsets.UTF_8));
System.out.println(prettyBinary(result, 8, " "));
}
public static String convertByteArraysToBinary(byte[] input) {
StringBuilder result = new StringBuilder();
for (byte b : input) {
int val = b;
for (int i = 0; i < 8; i++) {
result.append((val & 128) == 0 ? 0 : 1); // 128 = 1000 0000
val <<= 1;
}
}
return result.toString();
}
public static String prettyBinary(String binary, int blockSize, String separator) {
//... same with 1.1
}
}
輸出
01100001
困難的部分是這段代碼。這個想法類似于這個Java – Convert Integer to Binary using bit masking。在Java中,byte一個是8位,int一個是32位,對于整數128二進制是1000 0000.
for (byte b : input) {
int val = b; // byte -> int
for (int i = 0; i < 8; i++) {
result.append((val & 128) == 0 ? 0 : 1); // 128 = 1000 0000
val <<= 1; // val = val << 1
}
}
這&是一個按位與運算符,只有1 & 1,1其他組合都是0。
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
這val <<= 1實際上是val = val << 1,它是一個位左移運算符,它將位向左移動 1 位。
查看以下草稿:讓我們假設 是val一個int,或者byte代表一個字符a。
00000000 | 00000000 | 00000000 | 01100001 # val = a in binary
00000000 | 00000000 | 00000000 | 10000000 # 128
& # bitwise AND
00000000 | 00000000 | 00000000 | 00000000 # (val & 128) == 0 ? 0 : 1, result = 0
00000000 | 00000000 | 00000000 | 11000010 # val << 1
00000000 | 00000000 | 00000000 | 10000000 # 128
& # bitwise AND
00000000 | 00000000 | 00000000 | 10000000 # (val & 128) == 0 ? 0 : 1, result = 1
00000000 | 00000000 | 00000001 | 10000100 # val << 1
00000000 | 00000000 | 00000000 | 10000000 # 128
&
00000000 | 00000000 | 00000000 | 10000000 # result = 1
00000000 | 00000000 | 00000011 | 00001000 # val << 1
00000000 | 00000000 | 00000000 | 10000000 # 128
&
00000000 | 00000000 | 00000000 | 00000000 # result = 0
00000000 | 00000000 | 00000110 | 00010000 # val << 1
00000000 | 00000000 | 00000000 | 10000000 # 128
&
00000000 | 00000000 | 00000000 | 00000000 # result = 0
00000000 | 00000000 | 00001100 | 00100000 # val << 1
00000000 | 00000000 | 00000000 | 10000000 # 128
&
00000000 | 00000000 | 00000000 | 00000000 # result = 0
00000000 | 00000000 | 00011000 | 01000000 # val << 1
00000000 | 00000000 | 00000000 | 10000000 # 128
&
00000000 | 00000000 | 00000000 | 00000000 # result = 0
00000000 | 00000000 | 00110000 | 10000000 # val << 1
00000000 | 00000000 | 00000000 | 10000000 # 128
&
00000000 | 00000000 | 00000000 | 10000000 # result = 1
# collect all bits # 01100001
對于字符串,a二進制字符串是01100001.
在Java中,我們可以使用Integer.parseInt(str, 2)將二進制字符串轉換為字符串。
package com.mkyong.crypto.bytes;
import java.util.Arrays;
import java.util.stream.Collectors;
public class StringToBinaryExample3 {
public static void main(String[] args) {
String input = "01001000 01100101 01101100 01101100 01101111";
// Java 8 makes life easier
String raw = Arrays.stream(input.split(" "))
.map(binary -> Integer.parseInt(binary, 2))
.map(Character::toString)
.collect(Collectors.joining()); // cut the space
System.out.println(raw);
}
}
輸出
Hello
我們可以使用 Unicode 來表示非英文字符,因為 Java String 支持 Unicode,我們可以使用相同的位掩碼技術將 Unicode 字符串轉換為二進制字符串。
本例將單個漢字你(英文的意思you)轉換為二進制字符串。
package com.mkyong.crypto.bytes;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class UnicodeToBinary1 {
public static void main(String[] args) {
byte[] input = "你".getBytes(StandardCharsets.UTF_8);
System.out.println(input.length); // 3, 1 Chinese character = 3 bytes
String binary = convertByteArraysToBinary(input);
System.out.println(binary);
System.out.println(prettyBinary(binary, 8, " "));
}
public static String convertByteArraysToBinary(byte[] input) {
StringBuilder result = new StringBuilder();
for (byte b : input) {
int val = b;
for (int i = 0; i < 8; i++) {
result.append((val & 128) == 0 ? 0 : 1); // 128 = 1000 0000
val <<= 1;
}
}
return result.toString();
}
public static String prettyBinary(String binary, int blockSize, String separator) {
//... same code 1.1
}
}
輸出
3
111001001011110110100000
11100100 10111101 10100000
不同的 Unicode 需要不同的字節,并不是所有的漢字都需要 3 個字節的存儲,有些可能需要更多或更少的字節。
閱讀評論以獲得不言自明。
package com.mkyong.crypto.bytes;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class UnicodeToBinary2 {
public static void main(String[] args) {
String binary = "111001001011110110100000"; // 你, Chinese character
String result = binaryUnicodeToString(binary);
System.out.println(result.trim());
}
// <= 32bits = 4 bytes, int needs 4 bytes
public static String binaryUnicodeToString(String binary) {
byte[] array = ByteBuffer.allocate(4).putInt( // 4 bytes byte[]
Integer.parseInt(binary, 2)
).array();
return new String(array, StandardCharsets.UTF_8);
}
}
輸出
你
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習