更新时间:2022-12-13 12:05:59 来源:极悦 浏览2382次
将字符串转换为其二进制格式的步骤。
将字符串转换为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天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习