java: converting binary to text? - java

I wrote this code for converting binary to text .
public static void main(String args[]) throws IOException{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a binary value:");
String h = b.readLine();
int k = Integer.parseInt(h,2);
String out = new Character((char)k).toString();
System.out.println("string: " + out);
}
}
and look at the output !
Enter a binary value:
0011000100110000
string: ?
what's the problem?

instead of
String out = new Character((char)k).toString();
do
String out = String.valueOf(k);
EDIT:
String input = "011000010110000101100001";
String output = "";
for(int i = 0; i <= input.length() - 8; i+=8)
{
int k = Integer.parseInt(input.substring(i, i+8), 2);
output += (char) k;
}

Even Simpler:
String out=""+k;

Related

Storing a String with ASCII values into an Array and use RSA key

I am fairly new to coding. I am trying to take a user input, change their text into ASCII values, and then encrypt this with an RSA key i made.
Currently i have this code:
public class RSA {
public static void main(String args[]){
int p = 11;
int q = 17;
int n = p*q; //187
int phi = (p-1)*(q-1); //160
int e = 7;
int d = 23;
Scanner input = new Scanner(System.in);
System.out.println("Please enter your message: ");
String clearMsg = input.nextLine();
String trimmedClearMsg = new String(clearMsg.trim());
StringBuilder sb = new StringBuilder();
for (char c : trimmedClearMsg.toCharArray())
sb.append(String.format("%03d",(int)c));
BigInteger asciiMsg = new BigInteger(sb.toString());
System.out.println(asciiMsg); /*i print this out to check i have transferred to ASCII */
byte[] asciiArray = asciiMsg.toByteArray();
for (int i = 0; i < asciiArray.length; i++) {
double keyCipher = Math.pow(i, e)%n;
System.out.println(keyCipher);
}
}
Current output is:
Please enter your message:
hello
104101108108111 (this is the ASCII value of hello)
0.0
1.0
128.0
130.0
115.0
146.0
I am not sure why this is printing these numbers, i am expecting the encrypted version of 104101108108111.
Any guidance will be appreciated!! :)
This works (assuming that you got RSA details right):
public class RSA {
public static void main(String args[]) {
int p = 11, q = 17;
int n = p * q; //187
int phi = (p - 1) * (q - 1); //160
int e = 7, d = 23;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your message: ");
String msg = input.nextLine().trim();
byte[] msgBytes = msg.getBytes();
byte[] encryptedBytes = new byte[msgBytes.length];
for (int i = 0; i < msgBytes.length; i++) {
//below works only because n==187
encryptedBytes[i] = (byte) (Math.pow(msgBytes[i], e) % n);
}
System.out.println("Encrypted string : " + new String(encryptedBytes));
System.out.println("Encrypted string base64 : " + new String(Base64.getEncoder().encode(encryptedBytes)));
}
}
please note it uses Base64 which is avaliable from Java 8 onwards.

Same code giving runtime error if i am using bufferedreader instead of scanner

class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{//BigInteger bi1, bi2, bi3;
long t,j,n;
int i,x;
BigInteger u,sum,temp,m;
BigInteger[] a=new BigInteger[100009]; long[] b=new long[100009];
long mm=1000000007,f;
Scanner har=new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
t=har.nextInt();
for(f=0;f<t;f++)
{ temp = BigInteger.valueOf(1); sum = BigInteger.valueOf(0); u = BigInteger.valueOf(0);
n=har.nextInt(); x=har.nextInt(); m=har.nextBigInteger();//String line = br.readLine();
//String line = br.readLine(); // to read multiple integers line
//String[] strs = line.trim().split("\\s+");
//String[] s1 = br.readLine().split(" ");
//StringTokenizer st = new StringTokenizer(br.readLine());
for(i=1;i<=n;i++)
{b[i]=har.nextInt();
// b[i] = Integer.parseInt(st.nextToken());
//b[i] = Long.parseLong(System.console().readLine());
//b[i]=Long.parseLong(s1[i-1]);
}
}
}
}
input is of form
t
n x m
a[1] a[2] a[3] .......a[n]
This code is running correctly for scanner but if i try to use buffered reader or string tokenizer it is giving runtime error .
I am new to java and i need to use big integer for further part of the question.
There is nothing wrong with your code. You are defining the BufferReader as BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); and reading String as br.readLine();.
This snippet works absolutely fine and prints the input string back to the console:
public static void main (String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(br.readLine());
}
Some of the possibilities where you can get errors:
StringTokenizer
StringTokenizer st = new StringTokenizer(br.readLine());
Before passing it to the StringTokenizer make sure that you get a String back from br.readLine().
String text = br.readLine();
if(!StringUtils.isEmpty(text)) {
StringTokenizer st = new StringTokenizer(br.readLine());
/* Rest of the code */
}
Loop Condition Variable
for(i=1;i<=n;i++)
I do not see anything for BufferedReader which initializes n. Make sure you initialize it correctly.
Here is a quick code snippet:
public static void main (String[] args) throws Exception
{
long j, n, f, mm = 1000000007;
int i, x;
BigInteger u, sum, temp, m;
BigInteger[] a = new BigInteger[100009]; long[] b=new long[100009];
Scanner har = new Scanner(System.in);
long t = har.nextInt();
for(f=0;f<t;f++)
{
temp = BigInteger.valueOf(1);
sum = BigInteger.valueOf(0);
u = BigInteger.valueOf(0);
n = har.nextInt();
x = har.nextInt();
m = har.nextBigInteger();
/* Goto Next Line */
har.nextLine();
/* Start Reading Line */
String text = har.nextLine();
System.out.println("String Value: " + text);
if(null != text) {
StringTokenizer st = new StringTokenizer(text);
for(i = 1; i <= n; i++)
{
b[i] = Integer.parseInt(st.nextToken());
System.out.println("Value of b[" + i + "] = " + b[i]);
}
}
}
}

Swap the word in the String

input:-
1
Ans kot
Output:-
kot Ans
INPUT :
the first line of the input contains the number of test cases. Each test case consists of a single line containing the string.
OUTPUT :
output the string with the words swapped as stated above.**
Code:-
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.next();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
What is wrong in my code ? above is code which i am trying.
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
this snippet of your code is only gonna reverse the sentence "word by word" not "character by character". therefore, you need reverse the string (my[j]) before you append it into the StringBuffer
Use this
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
sc.nextLine();
StringBuffer result = new StringBuffer();
for (int i = 0; i < a; i++) {
String b = sc.nextLine();
String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
r.append(my[j] + " ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
}
Multiple things:
You are using next api which will just read your string that you type word by word and you loop until a i.e. in your example just once. So instead use nextLine api which will read whole line instead of just a word and then split by space:
String b = sc.nextLine();
You are reading input with nextInt api followed by enter, you you might sometime end up having return character when reading next token using next api. Instead use:
int a = Integer.parseInt(sc.nextLine());
You are using StringBuffer which has an overhead of obtaining mutex and hence should use StringBuilder.
Takes String input and return String in reverse order of each characters.
String reverse(String x) {
int i = x.length() - 1;
StringBuilder y = new StringBuilder();
while (i >= 0) {
y.append(x.charAt(i));
i--;
}
return y.toString();
}
public static String reverseWords(String input) {
Deque<String> words = new ArrayDeque<>();
for (String word: input.split(" ")) {
if (!word.isEmpty()) {
words.addFirst(word);
}
}
StringBuilder result = new StringBuilder();
while (!words.isEmpty()) {
result.append(words.removeFirst());
if (!words.isEmpty()) {
result.append(" ");
}
}
return result.toString();
}
You can run this code:
String[] splitted = yourString.split(" ");
for (int i = splitted.length-1; i>=0; i--){
System.out.println(splitted[i]);
}
Code:-
Scanner sc =new Scanner(System.in);
int a =Integer.parseInt(sc.nextLine());
StringBuffer result= new StringBuffer();
for (int i = 0; i <a; i++) {
String b=sc.nextLine();
String my[]= b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length-1; j >0; j--) {
r.append(my[j]+" ");
}
r.append(my[0] + "\n");
result.append(r.toString());
}
System.out.println(result.toString());
enter code here

Caesar cipher in Java

I'm trying to implement the Caesar cipher.
But while doing so I am getting an unexpected output which I am unable to rectify.
Will someone help me please?
My code is as follows:
import java.io.*;
public class encryptology
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t, move = Integer.parseInt(br.readLine());
String s = "", st = br.readLine();
int l = st.length();
for(int x = 0; x < l; x++){
char c = st.charAt(x);
t = (int)c;
if(move != 0){
t = t + move;
if(t > 90){
t = t - 26;
}
if(t < 65){
t += 26;
}
c = (char)t;
s = st + c;
}
}
System.out.println(s);
}
}
I entered move = 2 and st = charles
The output was: charles[
You are changing wrong string. You are acctualy setting result with starting string st and add encrypted char. Change
s=st+c;
to
s=s+c;

Hex to ASCII showing different result to correct PHP implementaiton

I needed a method that would convert hex to ascii, and most seem to be a variation of the following:
public String hexToAscii(String hex) {
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
for(int i = 0; i < hex.length() - 1; i += 2){
String output = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
temp.append(decimal);
}
return sb.toString();
}
The idea is to look at
hexToAscii("51d37bdd871c9e1f4d5541be67a6ab625e32028744d7d4609d0c37747b40cd2d");
If I print the result out, I get
-Í#{t7?`Ô×D?2^b«¦g¾AUM??Ý{ÓQ.
This is not the result I am needing though. A friend got the correct result in PHP which was the string reverse of the following:
QÓ{݇žMUA¾g¦«b^2‡D×Ô`7t{#Í-
There are clearly characters that his hexToAscii function is encoding whereas mine is not.
Not really sure why this is the case, but how can I implement this version in Java?
Assuming your input string is in, I would use a method like this
public static byte[] decode(String in) {
if (in != null) {
in = in.trim();
List<Byte> bytes = new ArrayList<Byte>();
char[] chArr = in.toCharArray();
int t = 0;
while (t + 1 < chArr.length) {
String token = "" + chArr[t] + chArr[t + 1];
// This subtracts 128 from the byte value.
int b = Byte.MIN_VALUE
+ Integer.valueOf(token, 16);
bytes.add((byte) b);
t += 2;
}
byte[] out = new byte[bytes.size()];
for (int i = 0; i < bytes.size(); ++i) {
out[i] = bytes.get(i);
}
return out;
}
return new byte[] {};
}
And then you could use it like this
new String(decode("51d37bdd871c9e1f4d5541be67a6ab625e"
+"32028744d7d4609d0c37747b40cd2d"))
How about trying like this:
public static void main(String[] args) {
String hex = "51d37bdd871c9e1f4d5541be67a6ab625e32028744d7d4609d0c37747b40cd2d";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);
}

Categories

Resources