- Преобразование строки (например, test123) в двоичный файл на Java
- Ответ 2
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Convert Text to Binary
- Convert Text to Binary
- Convert Text to Binary
- Tutorials
- Java – Преобразование строки в двоичный код
- 1. Преобразование строки в двоичный код – Преобразование строки в двоичный код –
- 2. Преобразуйте строку в двоично–разрядную маскировку.
- 3. Преобразуйте двоичный файл в строку.
- 4. Преобразуйте строку Юникода в двоичную.
- 5. Преобразуйте двоичный код в строку Юникода.
- Рекомендации
- Читайте ещё по теме:
Преобразование строки (например, test123) в двоичный файл на Java
Обычный способ — использовать String#getBytes() для получения базовых байтов, а затем представить эти байты в другой форме (hex, binary whatever).
Обратите внимание, что getBytes() использует кодировку по умолчанию, поэтому, если вы хотите, чтобы строка была преобразована в определенную кодировку символов, вы должны использовать getBytes(String encoding) вместо этого, но много раз (esp при работе с ASCII) getBytes() достаточно ( и имеет то преимущество, что не выбрасывает проверенное исключение).
Для конкретного преобразования в двоичный файл, вот пример:
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 binary.append(' '); > System.out.println("'" + s + "' to binary: " + binary);
Запуск этого примера даст:
'foo' to binary: 01100110 01101111 01101111
Ответ 2
private static final Charset UTF_8 = Charset.forName("UTF-8"); String text = "Hello World!"; byte[] bytes = text.getBytes(UTF_8); System.out.println("bytes= "+Arrays.toString(bytes)); System.out.println("text again post-104 post type-post status-publish format-standard has-post-thumbnail hentry category-uncategorized"> Ответ 3
A String
в Java можно преобразовать в "двоичный" с помощью метода getBytes(Charset)
.
byte[] encoded = "こんにちは、世界!".getBytes(StandardCharsets.UTF_8);
Аргумент этого метода является "кодировкой символов"; это стандартизованное сопоставление между символом и последовательностью байтов. Часто каждый символ кодируется в один байт, но не хватает уникальных байтовых значений для представления каждого символа на каждом языке. Другие кодировки используют несколько байтов, поэтому они могут обрабатывать более широкий диапазон символов.
Обычно используемая кодировка будет определяться определенным стандартом или протоколом, который вы реализуете. Если вы создаете свой собственный интерфейс и имеете свободу выбора, "UTF-8" - это простая, безопасная и широко поддерживаемая кодировка.
- Это легко, потому что вместо того, чтобы включать какой-либо способ отметить кодировку каждого сообщения, вы можете по умолчанию использовать UTF-8.
- Это безопасно, потому что UTF-8 может кодировать любой символ, который может использоваться в символьной строке Java.
- Он широко поддерживается, потому что он является одним из небольшого количества кодировок символов, которые должны присутствовать в любой реализации Java, вплоть до J2ME. Большинство других платформ поддерживают его, и он используется по умолчанию в таких стандартах, как XML.
Ответ 4
Вот мои решения. Их преимущества заключаются в следующем: простой код понимания, работает для всех персонажей. Наслаждайтесь.
public static void main(String[] args) < String str = "CC%"; String result = ""; char[] messChar = str.toCharArray(); for (int i = 0; i < messChar.length; i++) < result += Integer.toBinaryString(messChar[i]) + " "; >System.out.println(result); >
Возможность выбора количества отображаемых бит за char.
public static String toBinary(String str, int bits) < String result = ""; String tmpStr; int tmpInt; char[] messChar = str.toCharArray(); for (int i = 0; i < messChar.length; i++) < tmpStr = Integer.toBinaryString(messChar[i]); tmpInt = tmpStr.length(); if(tmpInt != bits) < tmpInt = bits - tmpInt; if (tmpInt == bits) < result += tmpStr; >else if (tmpInt > 0) < for (int j = 0; j < tmpInt; j++) < result += "0"; >result += tmpStr; > else < System.err.println("argument 'bits' is too small"); >> else < result += tmpStr; >result += " "; // separator > return result; >
public static void main(String args[])
01000011 01000011 00100101
Ответ 5
import java.lang.*; import java.io.*; class d2b < public static void main(String args[]) throws IOException< BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the decimal value:"); String h = b.readLine(); int k = Integer.parseInt(h); String out = Integer.toBinaryString(k); System.out.println("Binary: " + out); >>
Ответ 6
public class Test < public String toBinary(String text) < StringBuilder sb = new StringBuilder(); for (char character : text.toCharArray()) < sb.append(Integer.toBinaryString(character) + "\n"); >return sb.toString(); > >
Ответ 7
Во время игры с ответами, которые я нашел здесь, чтобы ознакомиться с этим, я немного исказил решение Nuoji, чтобы я мог быстрее понять его, глядя на него в будущем.
public static String stringToBinary(String str, boolean pad ) < byte[] bytes = str.getBytes(); StringBuilder binary = new StringBuilder(); for (byte b : bytes) < binary.append(Integer.toBinaryString((int) b)); if(pad) < binary.append(' '); >> return binary.toString(); >
Ответ 8
> int no=44; > String bNo=Integer.toString(no,2);//binary output 101100 > String oNo=Integer.toString(no,8);//Oct output 54 > String hNo=Integer.toString(no,16);//Hex output 2C > > String sBNo="101100"; > no=Integer.parseInt(sBNo,2);//binary to int output 44 > String sONo="54"; > no=Integer.parseInt(sONo,8);//oct to int output 44 > String sHNo="2C"; > no=Integer.parseInt(sHNo,16);//hex to int output 44
Ответ 9
public class HexadecimalToBinaryAndLong < public static void main(String[] args) throws IOException< BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the hexa value!"); String hex = bf.readLine(); int i = Integer.parseInt(hex); //hex to decimal String by = Integer.toBinaryString(i); //decimal to binary System.out.println("This is Binary: " + by); >>
Ответ 10
Вы также можете сделать это с помощью хорошего метода ol:
String inputLine = "test123"; String translatedString = null; char[] stringArray = inputLine.toCharArray(); for(int i=0;i
Convert Text to Binary
In this section, we will learn how to convert Text to Binary. The following program provides you the functionality to convert Text to Binary.

Convert Text to Binary
In this section, we will learn how to convert Text to Binary. The following program provides you the functionality to convert Text to Binary.

Convert Text to Binary
In this section, we will learn how to convert Text to Binary. The following program provides you the functionality to convert Text to Binary.
In the program code below, to take the input from the keyboard we have used BufferReader() method in which we have passed an object of it which is InputStreamReader() as must be knowing. Then we have defined a variable of type int which will convert the input to integer line by line. Now we have used a loop here to check the number we well input. It will take maximum of 24 bytes as we have declared maxBytes=3. Hence it will convert the number into bytes one by one.
Here is the code of the program:
import java.io.*; public class TexttoBinary <
private static final int maxBytes = 3 ;
public static void main ( String [] args ) < BufferedReader in =
new BufferedReader ( new InputStreamReader ( System.in )) ;
do <
try <
System.out.print ( "Type the number to parse: " ) ;
int number = Integer.parseInt ( in.readLine ()) ;
int Bit;
String result = "" ;
for ( int i = maxBytes* 8 ; i >= 0 ; i-- ) <
Bit = 1 if ( number >= Bit ) <
result += 1 ;
number -= Bit;
>
else <
result += 0 ;
>
>
System.out.println ( result ) ;
>
catch ( NumberFormatException e ) <
System.exit ( 0 ) ;
>
catch ( IOException e ) <
e.printStackTrace () ;
System.exit ( 1 ) ;
>
>
while ( true ) ;
>
>
Output of the program:
Tutorials
- Convert Decimal into Binary
- Convert Decimal to Octal
- Convert Decimal to Hexadecimal
- Convert Binary to Decimal
- Convert Binary to Hexadecimal
- Convert Octal to Decimal
- Convert Hexadecimal to Decimal
- Convert Date To Calendar
- Convert Date to Milliseconds
- Convert Hexadecimal number into Integer
- Convert Hexadecimal into Binary and Long
- Convert an Integer into a String
- Convert a String into an Integer Data
- Convert a Character into the ASCII Format
- Convert Character into Integer
- Alphabet Character Case-Converter
- Convert Character into a String
- Convert String to Date
- Convert Date to Long
- Convert Date to String
- Convert String to Calendar
- Convert Milliseconds to Date
- Convert Date to Timestamp
- Convert Long to Date
- Convert Date to GMT
- Convert InputStream to Byte
- Convert InputStream to BufferedReader
- Convert Inputstream to OutputStream
- Convert InputStream to ByteArray
- Convert Inputstream to ByteArrayInputStream
- Convert InputStream to File
- Convert String to Date
- Convert Char To Byte
- Convert Double To String
- Convert ArrayList To Array
- Convert Boolean to String
- Convert Decimal to Integer
- Convert Float to Integer
- Convert Integer to Double
- Convert Integer to Float
Java – Преобразование строки в двоичный код
В этой статье показано, как использовать Integer.toBinaryString или битовая маскировка для преобразования строки в двоичный строковый представитель.
В этой статье показаны пять примеров преобразования строки в двоичную строку или наоборот.
- Преобразовать строку в двоичный код – Преобразовать строку в двоичный код –
- Преобразование строки в двоичный код – Немного Маскировки Преобразовать двоичный файл в строку –
- Целое число.Синтаксический анализ
- Преобразуйте строку Юникода в двоичную.
1. Преобразование строки в двоичный код – Преобразование строки в двоичный код –
Шаги по преобразованию строки в двоичный формат.
- Преобразуйте строку в символ[] .
- Зацикливает символ[] .
- Целое число.toBinaryString(символ) для преобразования символов в двоичную строку.
- 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) < Listresult = 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
2. Преобразуйте строку в двоично–разрядную маскировку.
2.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 > return result.toString(); > public static String prettyBinary(String binary, int blockSize, String separator) < //. same with 1.1 >>
Самое сложное – это этот код. Идея похожа на эту Java – Преобразование целого числа в двоичное с помощью битовой маскировки . В Java/|байт является 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 & 1 является 1 , другие комбинации – это все 0 .
1 & 1 = 1 1 & 0 = 0 0 & 1 = 0 0 & 0 = 0
Просмотрите следующий проект: давайте предположим, что val – это int , или байт представляет символ 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
Для строки a двоичная строка – это 01100001 .
3. Преобразуйте двоичный файл в строку.
В 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); > >
4. Преобразуйте строку Юникода в двоичную.
Мы можем использовать Юникод для представления неанглийских символов, поскольку строка Java поддерживает Юникод, мы можем использовать ту же технику битовой маскировки для преобразования строки Юникода в двоичную строку.
В этом примере преобразуется один китайский иероглиф 你 (Это означает вы на английском языке) в двоичную строку.
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 > return result.toString(); > public static String prettyBinary(String binary, int blockSize, String separator) < //. same code 1.1 >>
3 111001001011110110100000 11100100 10111101 10100000
Для разных Юникодов требуются разные байты, и не для всех китайских символов требуется 3 байта памяти, некоторым может потребоваться больше или меньше байтов.
5. Преобразуйте двоичный код в строку Юникода.
Прочитайте комментарии для пояснения.
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()); >// >
Рекомендации
- Википедия – битовая маскировка
- Википедия – Побитовая И
- Википедия – Юникод
- Java – Преобразование целых чисел в двоичные использование битовой маскировки
- Ява – Как преобразовать массивы байтов в шестнадцатеричный
Читайте ещё по теме: