How to convert (English) String to binary form using java? - java

I have a text file, which is divided in 3 part, and now I want to convert this divided block to binary format and store in database.
Please help me to solve this problem.
Thanks.
String firstblock = “If debugging is thae process of removing software bugs, then programming must be the process of putting them in. Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.”;
and I need firstblock in binary form.

String firstblock = “If debugging is thae process of removing software bugs, then programming must be the process of putting them in. Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.”;
byte[] bytes = firstblock.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 <<= 1;
}
binary.append(' ');
}
System.out.println(binary);
and you can check it binary to string

Use getBytes() method.
See the below
String text = "Hello World!";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Update:
Try with below code:
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 <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
Reference :
Convert A String (like testing123) To Binary In Java

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 <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
you try with this code if you want to use online tool
An English to binary translator is a tool that can convert text
written in the English language into a sequence of 0s and 1s, which is
known as binary code. This is the language that computers understand
and use to process and store data.
Here is an example of how it would work:
Input: "Hello" Output: "01001000 01100101 01101100 01101100 01101111"
The translator would take the word "Hello" and convert each letter
into its corresponding 8-bit binary code representation.

Related

Java - Binary decryption

beginner here! I was just wondering if anyone could help? I am currently writing a Encryption/Decryption programme in Java and need to reverse binary which is inputted. I have managed to do encrypt it into binary, however, I am struggling to now decrypt it (e.g - The word HELLO has been encrypted , but I now need to create a function so that it can read the binary and change it back to the text.)
Any help would be appreciated! This is the code I used for my original binary cipher in the encryption part.
String temp="";
for(int i=0;i<message.length();i++)
{
temp=Integer.toBinaryString(message.charAt(i));
for(int j=temp.length();j<8;j++)
{
temp="0"+temp;
}
encryptText+=temp+" ";
}
I have tried various different measures but being as I have just started out a little guidance would be hugely appreciated!
If you're just trying to get a fixed-length Binary String, try this:
private static String toBinaryString(final int value) {
final String binaryString = Integer.toBinaryString(value);
final char[] lead = new char[Integer.SIZE - binaryString.length()];
Arrays.fill (lead, '0');
return String.valueOf(lead).concat(binaryString);
}
If there would be no space between every group of 8 bits 0/1:
for (int i = 0; i + 7 < message.length(); i += 8) {
String temp = message.substring(i, i + 8);
int c = Integer.parseInt(temp, 2); // Base 2, binary
decryptText += (char)c;
}
Space separated:
for (String temp : message.split(" ")) {
if (!temp.isEmpty()) {
int c = Integer.parseInt(temp, 2); // Base 2, binary
decryptText += (char)c;
}
}

How to convert a string to binary utf-16 and Binary to String in java?

my project requires converting Arabic text to binary , then convert binary to text (reverse process).
I used this code,but I notice that when I use utf-16 to convert string to binary, then read this binary to convert it back to the original UTF-16 String will give me different chars
for example : the Arabic char used in encoding is (ن) which converted in binary (0100011000000110) by utf-16lE
now when I want to convert these binary bits(0100011000000110) to original utf-16 string will give me different character is F.
These problem just appears if the string is Arabic characters and utf-16 encoding. How I can solve this problem..?
// Convert the text to binary
public static String getBinaryFromText(String secretText) {
byte[] bytes = secretText.getBytes(StandardCharsets.UTF_16LE);
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 <<= 1;
}
}
return binary.toString();
}
// Convert the binary to text.
public static String getTextFromBinary(String binaryString) {
String binary = binaryString.replace(" ", "");
String binaryPer8Bits;
byte[] byteData;
byteData = new byte[binary.length() / 8];
for (int i = 0; i < binary.length() / 8; i++) {
// To divide the string into 8 characters
binaryPer8Bits = binary.substring(i * 8, (i + 1) * 8);
// The integer of decimal string of binary numbers
Integer integer = Integer.parseInt(binaryPer8Bits, 2);
// The casting to a byte type variable
byteData[i] = integer.byteValue();
}
return new String(byteData);
}
With new String(byteData); you interpret the create byte[] with default encoding. To interpret it as UTF_16LE you need to use a different constructor:
new String(byteData, StandardCharsets.UTF_16LE);
(Almost) never use the new String(byte[]) it will use the default encoding, so your application will be platform dependend.

write raw binary to file java

Say I have a binary string ("0 and 1s") and I want to write this string to a binary file, how can this be done in java? I tried converting to ASCII values string, then create a ByteArrayInputStream from that but values over 127 do not display correctly. Can anyone help me with this?
My binaryToAscii method:
public static String BinaryToAscii(String bin){
int num_of_bytes = bin.length()/8;
StringBuilder sb = new StringBuilder();
int index = 0;
String byte_code;
Character char_code;
for (int i =0; i<num_of_bytes;i++){
index = i*8;
byte_code = bin.substring(index,index+8);
int charCode = Integer.parseInt(byte_code, 2);
char_code = new Character((char)charCode);
sb.append(char_code);
}
return sb.toString();
}
Then I convert the returned string to a ByteArrayInputStream using
InputStream is = new ByteArrayInputStream(ascii.toString().getBytes());
you first would transform the 0 / 1 string to a byte[].
then write out using
DataOutputStream.writeByte().
read in with
DataInputStream.readUnsignedByte() // to get 0 - 255
To convert string to binary use this:
You will first need to break the string into its individual letters then run them through this one at a time.
char letter = c;
byte[] bytes = letter.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 <<= 1;
}
binary.append(' ');
}
System.out.println(binary);

converting a hex string back to a string, in Java

I am struggling trying to convert a hex number string back to the original string. I convert the string using the following method:
private static String hex(String binStr) {
String newStr = new String();
try {
String hexStr = "0123456789ABCDEF";
byte [] p = binStr.getBytes();
for(int k=0; k < p.length; k++ ){
int j = ( p[k] >> 4 )&0xF;
newStr = newStr + hexStr.charAt( j );
j = p[k]&0xF;
newStr = newStr + hexStr.charAt( j ) + " ";
}
} catch (Exception e) {
System.out.println("Failed to convert into hex values: " + e);
}
return newStr;
}
I am really stuck, and any advice would be greatly appreciated.
Thank you in advance
Consider this:
String hexStr = "0123456789ABCDEF";
long i = Long.valueOf(hexStr, 16);
System.out.println(Long.toHexString(i));
The code in the question destroys information. Only the most significant two bits and the least significant four bits of each input byte contribute to the result. That means it cannot, in general, be reversed.
If the right shift had been by four bits, instead of 6:
int j = ( p[k] >> 4 )&0xF;
all the input would have been preserved, and the original string could have been recovered from the hex string. Maybe you really meant the four bit shift?

How to convert binary to text in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Binary to text in Java
I'm writing a program that can convert multiple things, but I need help with the converting of binary. I have my code for text-to-binary working, but I'm not sure about binary-to-text. Here is my code for the button which triggers the conversion:
String code = jTextArea5.getText();
if (code == null) {
System.out.println(jTextArea1.getText( ));
String writing = jTextArea1.getText();
byte[] bytes = writing.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 <<= 1;
}
binary.append(' ');
}
jTextArea5.setText("" + binary);
}
else
{
System.out.println(jTextArea1.getText( ));
String binary = jTextArea1.getText();
int ascii = Integer.parseInt(binary, 2);
char character = (char)ascii;
jTextArea5.setText("" + character);
}
If anyone knows how I can fix this code to work, that'd be great. Thanks!
NOTE - This bit below works on it's own, just not in conjunction with any efforts to allow converting binary in jTextArea5 to text in jTextArea1.
System.out.println(jTextArea1.getText( ));
String writing = jTextArea1.getText();
byte[] bytes = writing.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 <<= 1;
}
binary.append(' ');
}
jTextArea5.setText("" + binary);
Convert the binary into an integer:
String binary = "010101";
int ascii = Integer.parseInt(binary, 2);
Then turn the integer into ascii:
char character = (char)ascii;
Swap the 5 and the 1 around so it grabs the binary out of the correct textbox.
And use StringTokenizer to process each block of 8
Dont forget to import StringTokenizer
else
{
System.out.println(jTextArea5.getText( ));
String binary = jTextArea5.getText();
StringTokenizer st = new StringTokenizer(binary," ");
while(st.hasMoreTokens()){
int ascii = Integer.parseInt(st.nextToken(), 2);
char character = (char)ascii;
jTextArea1.setText(jTextArea1.getText() + "" + character);
}
}
this bit checks whats in jTextArea5.getText()
if (code == null) {
change it to
if (code.equals("")) {
and make sure you clear out whats in the text boxes before you start either conversion

Categories