java string to bit_Java Convert String to Binary
This article shows you five examples to convert a string into a binary string representative or vice verse.
本文向您展示了五个示例,这些示例将字符串转换为二进制字符串表示形式,反之亦然。
Convert String to Binary – Integer.toBinaryString
Convert String to Binary – Bit Masking
Convert Binary to String – Integer.parseInt
Convert Unicode String to Binary.
Convert Binary to Unicode String.
1. Convert String to Binary – Integer.toBinaryString
The steps to convert a string to its binary format.
Convert string to char[].
Loops the char[].
Integer.toBinaryString(aChar) to convert chars to a binary string.
String.format to create padding if need.
package com.mkyong.convert;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StringToBinaryExample01 {
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)).replaceAll(" ", "0"));// char -> int, auto-cast zero pads
}
return result.toString();
}
public static String prettyBinary(String binary, int blockSize, String separator) {
List 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));
}
}
Output
0100100001100101011011000110110001101111
01001000 01100101 01101100 01101100 01101111
2. Convert String to Binary – Bit Masking.
2.1 This Java example will use bit masking technique to generate binary format from an 8-bit byte.
package com.mkyong.convert;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StringToBinaryExample02 {
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 00000
val <<= 1;
}
}
return result.toString();
}
public static String prettyBinary(String binary, int blockSize, String separator) {
List 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));
}
}
Output
01100001
The hard part is this code. The idea is similar to this Java – Convert Integer to Binary using bit masking. In Java, byte is an 8-bit, int is 32-bit, for integer 128 the binary is 1000 0000.
困难的部分是这段代码。这个想法类似于–使用位掩码将整数转换为二进制。在Java中,字节是8位,整数是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
}
}
This & is an Bitwise AND operator, only 1 & 1 is 1, other combinations are all 0.
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
This val <<= 1 is actually val = val << 1, it is a bit left shift operator, it moves the bits to the left side by 1 bit.
Review the following draft: let’s assume the val is an int, or byte represents a character 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
For string a the binary string is 01100001.
3. Convert Binary to String.
In Java, we can use Integer.parseInt(str, 2) to convert a binary string to a string.
package com.mkyong.crypto.bytes;
import java.util.Arrays;
import java.util.stream.Collectors;
public class StringToBinaryExample03 {
public static void main(String[] args) {
String input = "01001000 01100101 01101100 01101100 01101111";
// Java 11 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);
}
}
4. Convert Unicode String to Binary.
We can use Unicode to represent non-English characters since Java String supports Unicode, we can use the same bit masking technique to convert a Unicode string to a binary string.
由于Java String支持Unicode,因此可以使用Unicode来表示非英语字符,我们还可以使用相同的位掩码技术将Unicode字符串转换为二进制字符串。
This example converts a single Chinese character 你 (It means you in English) to a binary string.
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 UnicodeToBinary01 {
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) {
StringBuffer result = new StringBuffer();
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) {
List 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));
}
}
Output
3
111001001011110110100000
11100100 10111101 10100000
Different Unicode requires different bytes, and not all Chinese characters required 3 bytes of storage, some may need more or fewer bytes.
不同的Unicode需要不同的字节,并非所有汉字都需要3个字节的存储空间,有些可能需要更多或更少的字节。
5. Convert Binary to Unicode String.
Read comments for self-explanatory.
package com.mkyong.crypto.bytes;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class UnicodeToBinary02 {
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(Integer.parseInt(binary, 2)) // 4 bytes byte[]
.array();
return new String(array, StandardCharsets.UTF_8);
}
}
Output
你
java string to bit_Java Convert String to Binary相关推荐
- [Mybatis]Cannot convert string '\xAC\xED\x00\x05ur...' from binary to utf8mb3
在使用 Mybatis-Plus 的 Lambda 条件查询时,报出了这个 Cannot convert string '\xAC\xED\x00\x05ur...' from binary to u ...
- java jackson2.6_Jackson 2 - Convert Java Object to JSON and JSON String to Object
在本教程中,我们将学习使用将JSON转换为Java对象 – 并将Java对象转换为JSON . 1. Jackson 2 maven dependency 要将Jackson 2库包含在您的项目中,请 ...
- com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGI
报错如下: 2020-03-05 18:41:55.161 5576-5576/com.xiayiye.takeout W/System.err: com.google.gson.JsonSyntax ...
- 2个在Java中将Byte []数组转换为String的示例
将字节数组转换为String似乎很容易,但是很难做到正确. 每当字节转换为String或char时,许多程序员都会犯忽略字符编码的错误,反之亦然. 作为程序员,我们都知道计算机只能理解二进制数据,即0 ...
- Caused by: java.lang.NumberFormatException: For input string: “?2130969371“
Caused by: java.lang.NumberFormatException: For input string: "?2130969371" 题记报错. 上结论:&quo ...
- Java中将int数组转换为String数组
1.天真 天真的解决方案是创建一个String类型数组,并在将int转换为Strings后,使用常规的for循环从原始整数数组为其分配值. 1 2 3 4 5 6 7 8 9 10 11 12 13 ...
- 关于java.lang.NumberFormatException: For input string:${redis.maxIdle}的报错
项目通用文件配置目录 reids配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmln ...
- java new string 图_Java中String直接赋字符串和new String的一些问题
今天课堂测试做了几道String的练习题,做完直接心态爆炸...... 整理自下面两篇博客: 首先先来看看下面的代码: public classStringTest {public static vo ...
- java中的string函数_java中string.trim()函数的作用实例及源码
trim()的作用:去掉字符串首尾的空格. public static void main(String arg[]){ String a=" hello world "; Str ...
- java string s_Java字符串:“String s=新字符串(”愚蠢“);
Java字符串:"String s=新字符串("愚蠢"): 我是一个学习Java的C+的人.我正在阅读有效的Java,有些东西让我感到困惑.它说永远不要写这样的代码:St ...
最新文章
- javaweb学习总结(四十)——编写自己的JDBC框架
- Hadoop实战第四章--读书笔记
- FlexChart: 针对AJAX的Flash绘图应用
- 浅谈游戏自动寻路A*算法
- c++实现顺序表的相关操作
- oracle jdbc jar包_Oracle总结之plsql编程(基础七)
- 成本预算的四个步骤_全网推广步骤有哪些?
- 大数据学习笔记51:Flume Channel Selectors(Flume通道选择器)
- Oracle11g新特性:在线操作功能增强-可等待DDL操作
- java new 新对象_java基础(五)-----new一个对象的具体过程
- Visual Studio 2005 开发 Silverlight 1.0
- 互融云数字资产交易系统开发解决方案
- 2022吴恩达机器学习课程——第一课
- jquery editplus
- 浙江大学计算机科学排名,2017浙江大学专业排名结果
- 啥地方规定豆腐干豆腐
- iOS 6与iOS 7的增量更新的区别
- uniapp下载图片
- 四六级重要单词(二)
- Dialer拨号定制功能