Перевод строки в бинарный код на java
При переводе строки в бинарный код и обратно у меня все работает прекрасно в случае использования латинских символов. В случае перевода кириллицы, перевод в бинарный код срабатывает нормально, но перевод этого же кода обратно в текст не дает изначально введенного слова на кириллице.
public class Main {
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int x = 0;
System.out.println("1. Перевести текст в бинарный код.");
System.out.println("2. Перевести бинарный код в текст.");
x = in.nextInt();
if (x == 1) {
System.out.println("Введите ниже текст для перевода в бинарный код.");
Scanner in = new Scanner(System.in);
String s;
s = in.nextLine();
int d[] = new int[255];
for (int i = 0; i < s.length(); i++) {
d[i] = Integer.valueOf(s.charAt(i));
}
StringBuilder sb = new StringBuilder();
for (byte b : s.getBytes()) {
System.out.print(
String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0')
);
}
System.out.println(sb.toString());
} else if (x == 2) {
String str = in.nextLine();
System.out.println("Введите ниже бинарный код.");
String input = in.nextLine();
StringBuilder sb = new StringBuilder();
Arrays.stream(
input.split("(?<=\\G\\d{8})")
).forEach(st ->
sb.append((char) Integer.parseInt(st, 2))
);
String output = sb.toString();
Arrays.stream(input.split("(?<=\\G\\d{8})")).forEach(st -> System.out.print((char) Integer.parseInt(st, 2)));
System.out.print('\n');
}
}
}
Ответы (1 шт):
Автор решения: Aziz Umarov
→ Ссылка
Вот решение моё.
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int x = 0;
System.out.println("1. Перевести текст в бинарный код.");
System.out.println("2. Перевести бинарный код в текст.");
x = in.nextInt();
in.nextLine();
if (x == 1) {
System.out.println("Введите ниже текст для перевода в бинарный код.");
Scanner in = new Scanner(System.in);
String s;
s = in.nextLine();
byte[] bytes = s.getBytes();
String bynaryString =
IntStream.range(0, bytes.length)
.mapToObj(
idx ->
String.format(
"%08d", Integer.parseInt(Integer.toBinaryString(bytes[idx] & 0xFF))))
.collect(Collectors.joining());
System.out.println(bynaryString);
} else if (x == 2) {
String str = in.nextLine();
System.out.println("Введите ниже бинарный код.");
String input = in.nextLine();
Matcher matcher = Pattern.compile(".{1,8}").matcher(input);
byte[] backBytes =
matcher
.results()
.mapToInt(
result -> Integer.parseInt(input.substring(result.start(), result.end()), 2))
.collect(
ByteArrayOutputStream::new,
(baos, i) -> baos.write((byte) i),
(baos1, baos2) -> baos1.write(baos2.toByteArray(), 0, baos2.size()))
.toByteArray();
String sConverted = new String(backBytes, StandardCharsets.UTF_8);
System.out.printf(sConverted);
}
}

