0

please any one can help me to convert the ascciiText to binary such as 49 have binary 00110001 and 48 is 00110010 and so on this is my code

import java.lang.String;
import java.util.Scanner;
import java.lang.*;
import java.io.*;
import java.util.*;

public class encrption {

public static void main(String[] args){

     // INPUT: KeyText   (StrKey).
    // OUTPUT: Ciphertext (ConcatenatedData).
   //String ConcatenatedData; 


    // Read data from user.
    Scanner in = new Scanner(System.in);
    System.out.println("Enter Your PlainText");
    String StrValue = in.nextLine();
    System.out.println("Enter Your KeyText ");
    String StrKey = in.nextLine();

  // Print the Concatenated Data.

 String ConcatenatedData = StrKey.concat(StrValue);
       System.out.println("the Concatenated Data is :"+ConcatenatedData);

  // Convering the Concatenated data to Ascii data.

 try { 
  byte[] asciiText = ConcatenatedData.getBytes("US-ASCII");


    System.out.println(Arrays.toString(asciiText)); 

}

 catch (java.io.UnsupportedEncodingException e)
     { e.printStackTrace(); }

Please any one can help me to convert the series of ascciiText to binary such as 49 have binary 00110001 and 48 is 00110010 and so on

Configuration: encrption - JDK version 1.8.0_40

Enter Your PlainText welcome Enter Your KeyText 123 the Concatenated Data is :123welcome [49, 50, 51, 119, 101, 108, 99, 111, 109, 101]

Process completed.

1
  • 1
    Integer.toBinaryString()? Commented Sep 17, 2015 at 10:26

2 Answers 2

1

Simialr on @Paul's solution but written another way.

String toBinary(byte b) {
    StringBuilder sb = new StringBuilder(8);

    for(int i = 7 ; i >= 0 ; i--)
        sb.append((char) ('0' + ((b >> i) & 1));

    return sb.toString();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Since byte doesn't provide any method for this you'll have to use Integer:

byte[] b = ...;//you're array
String binStr = "";

for(byte v : b)
    binStr += Integer.toBinaryString(v);

Or you could write your own method. Wouldn't be too difficult aswell:

String toBinary(byte b){
    char[] binArr = new char[8];

    //if a bit is 1, emplace '1' at the respective position in the array, else 0
    for(int i = 0 ; i < 8 ; i++)
        binArr[7 - i] = (b & (1 << i)) == 0 ? '0' : '1';

    return new String(binArr);
}

3 Comments

when adding this line[String binStr = Integer.toBinaryString(ascciiText)] gives to me this error error: incompatible types: byte[] cannot be converted to int
the reason for this is pretty simple: Integer.toBinaryString() expects a numeric type as parameter, not an Array, as shown in the example. You'll have to iterate over the array and transform every single byte on its own
can you do it for me

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.