Converting string of number to Hex, Binary, and Decimal - java

I'm trying to answer the question below:
Use an array or ArrayList and generate 20 random numbers (Integer
values between 0 and 100. 100 not inclusive). The program should
perform the following tasks.
Write the numbers from the array or ArrayList to a file.
Read the numbers from the file and display them on the console in decimal, hexadecimal and binary.
So far I have the random generator working well, and the file is being written. As for re-reading the file and displaying the numbers from the file as hex, decimal and binary...I am completely lost. Here is that I have so far.
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
public class Write {
public static void main(String[] args) throws IOException {
Random generator = new Random();
ArrayList numList = new ArrayList();
int n = 0;
while( n < 20 ) {
int numGen = generator.nextInt(100);
numList.add(numGen);
n++;
}
String result = numList.toString().replaceAll("[\\[\\]]", "");
result = result.replace(",", " ");
System.out.print(result);
String filePath = "C:/Users/Username/Desktop/FileIOTest/coding_assignment.txt";
File f = new File(filePath);
FileOutputStream fileout = new FileOutputStream (f);
DataOutputStream dataOut = new DataOutputStream(fileout);
dataOut.writeBytes(result);
dataOut.close();
}
}

I guess you should try to complete the lines by yourself, so I only give you some basic input.
To read from file, three lines:
fileIn
dataIn
readBytes
These lines should be easy. To get the numbers, use
split
Integer.ParseInt
and to display, you may refer to
Integer.toHexString
Integer.toBinaryString

From your code, you have not started to write the code for Reading numbers from file.
Regarding reading the values, you can use BurreferReader to read numbers line by line. And then you can use String.split method to split the numbers into an array using split(" ")
Regarding converting int value to Binary and Hex mode, you can use the method toBinaryString and toHexString in Integer class, like
int i = 20;
System.out.println(i);//Print int value
System.out.println(Integer.toBinaryString(i)); //Print Binary string
System.out.println(Integer.toHexString(i)); // Print Hex string
Output in Console is as follows:
20
10100
14

To convert numbers to binary and hexadecimal from base 10, you can simply use the methods:
Integer.toBinaryString(n);
Integer.toHexString(n);
However, if you actually want to code these for yourself, try checking out the following website:
http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/toBaseK.html
It helps provide a simple algorithm that converts from base 10 to any other number base.

Related

In what format is data sent on, getInputStream on a URLconnection Object?

Im trying to connect to a php script on a server and retrieve the text the script echoes.Do accomplish I used the following code.
CODE:=
import java.net.*;
import java.io.*;
class con{
public static void main(String[] args){
try{
int c;
URL tj = new URL("http://www.thejoint.cf/test.php");
URLConnection tjcon = tj.openConnection();
InputStream input = tjcon.getInputStream();
while(((c = input.read()) != -1)){
System.out.print((char) c);
}
input.close();
}catch(Exception e){
System.out.println("Caught this Exception:"+e);
}
}
}
I do get the desired output that is the text "You will be Very successful".But when I remove the (char) type casting it yields a 76 digit long.
8911111732119105108108329810132118101114121321151179999101115115102117108108
number which I'm not able to make sense of.I read that the getInputStream is a byte stream, then should there be number of digits times 8 number long output?
Any insight would be very helpful, Thank you
It does not print one number 76 digits long. You have a loop there, it prints a lot of numbers, each up to three digits long (one byte).
In ASCII, 89 = "Y", 111 = "o" ....
What the cast to char that you removed did was that it interpreted that number as a Unicode code point and printed the corresponding characters instead (also one at a time).
This way of reading text byte by byte is very fragile. It basically only works with ASCII. You should be using a Reader to wrap the InputStream. Then you can read char and String directly (and it will take care of character sets such as Unicode).
Oh I thought it would give out the byte representation of the individual letter.
But that's exactly what it does.
You can see it more clearly if you use println instead of print (then it will print each number on its own line).

how to store and retrieve a 8 bit binary value into a bin file using java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Jesper {
public static void main(String[] args) throws IOException {
try (OutputStream out = new FileOutputStream("example.bin")) {
out.write(10100001);
out.write(10000001);
}
}
}
i am storing 8 bit= 1 byte values- 10100001 and 10000001 in to the bin file example.bin.
on executing this 21,81 are stored in the bin file. which is wrong. how to store these exact values and retrieve them?
No, you're storing the integers "ten million, one hundred thousand and one" 10,100,001 and "ten million and one" 10,000,001. If you want these numbers to be binary, you need to tell Java: 0b10100001 and 0b10000001. But Java will still think they're integers, you need to tell it that they're bytes.
But out.write() expects a String object. While it is happy to convert a char into a string, if it sees a byte it wil convert it into a number.
out.write((char)0b10100001);
out.write((char)0b10000001);
For example:
String s;
for (char c=0b00000000;c<0b100000000;++c) {
s = s + c;
} // for
out.write(s);
Check the above code: does it write 128 bytes to your binary file?

How to write a one-byte value in a binary file-java

I have tried a lot with many ways to write a program that : write a one byte value in a file as it is.. for example write 01010101 in a file.. then i want to read the file and print what i wrote.So it should display 01010101. None of my codes worked so. Any help?
Because i am writing a compression program it essential to be 1 byte and not 8
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main2 {
public static void main(String[] args) throws Exception {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("Text.t"));
dos.writeBytes(String.valueOf(01010101));
File file = new File("Text.t");
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
System.out.println(br.readLine());
dos.close();
br.close();
}
}
It works well with binary code that starst with 1 but with 0 not.. for example for 01010101 it shows 266305
The problem with "It works well with binary code that starst with 1 but with 0 not.. for example for 01010101 it shows 266305" is that 01010101 is an octal literal and is read in by the compiler as base-8 (aka Octal).
Use 1010101 when writing the literal - leading zeros mean nothing to numbers; but they do mean something to how the Java code is parsed!
Decimal numbers that are displayed as "00xyz" are often zero-padded, which is applied to the string representation; the number itself is xyz.
From the comment I believe the desired operation is to use a binary literal. You'll have to emit this using a "bit converter" to display as expected - the bit converter will take the value of eg. 0b11 (integer 3) and turn it into a string "11". You may also want to apply a padding with an assumed output width - again, 0b01 == 0b1 and the leading 0 means nothing to an integer.
The following will emit the decimal string representation of the huffman bit sequence, without any leading zeros. However this when paired with above should get you off on the right track.
dos.writeBytes(String.valueOf(0b01001010));
I would use a Byte representation for radix 2 e.g. Byte.parseByte("00010001", 2).
But the problem is Java's primitives are signed numbers so it won't work for negative values (when first digit is 1), thus Byte.parseByte("10010011", 2) will throw a NumberFormatException.
The trick here is to initially replace leading digit (if it is 1, with 0), parse it and then set the bit again to 1. Then store this byte to your file.
private static byte binaryStringToByte(String s) {
//also check for null, length = 8, contain 0/1 only etc.
if (s.startsWith("0")) {
return Byte.parseByte(s, 2);
} else {
StringBuilder sBuilder = new StringBuilder(s);
sBuilder.setCharAt(0, '0');
byte temp = Byte.parseByte(sBuilder.toString(), 2);
return (byte) (temp | (1 << 7));
}
}
Then, to get the binary String representation of a byte use this code:
byte b = binaryStringToByte("10001000");
String s1 = String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');

generate random binary data such 23ABFF

I want to generate binary data the similar to OData binary and I not sure how.
the type is defined as
Represent fixed- or variable- length binary data
binary'[A-Fa-f0-9][A-Fa-f0-9]*' OR X '[A-Fa-f0-9][A-Fa-f0-9]*' NOTE: X and binary are case sensitive. Spaces are not allowed between binary and the quoted portion. Spaces are not allowed between X and the quoted portion. Odd pairs of hex digits are not allowed.
**Example 1: X'23AB' Example 2: binary'23ABFF'**
with the next.random() Im not sure which type can be appropriate .
any idea?
new Random().nextBytes(byte[])
EDIT: You can also achieve this with
new Random().nextInt(16)
See:
int nbDigitsYouWant=8;
Random r=new Random();
for(int i=0;i<nbDigitsYouWant;i++){
//display hexa representation
System.out.print(String.format("%x",r.nextInt(16)));
}
Output:
ea0d3b9d
EDIT : Here is a quick and dirty example with random bytes sent to a DataOutputStream.
public static void main(String[] args) throws Exception{
DataOutputStream dos=new DataOutputStream(new FileOutputStream("/path/to/your/file"));
int nbDesiredBytes=99999999;
int bufferSize=1024;
byte[] buffer = new byte[bufferSize];
Random r=new Random();
int nbBytes=0;
while(nbBytes<nbDesiredBytes){
int nbBytesToWrite=Math.min(nbDesiredBytes-nbBytes,bufferSize);
byte[] bytes=new byte[nbBytesToWrite];
r.nextBytes(bytes);
dos.write(bytes);
nbBytes+=nbBytesToWrite;
}
dos.close();
}

How do I decode a string from base 32 to a BigInteger

I tried the following code:
import java.math.BigInteger;
import org.apache.commons.codec.binary.Base32;
import org.junit.Test;
public class Sandbox
{
#Test
public void testSomething() {
String sInput = "GIYTINZUHAZTMNBX";
BigInteger bb = new BigInteger(new Base32().decode(sInput));
System.out.println("number = " + bb);
}
}
and heres the output:
number = 237025977136523702055991
using this website to convert between base 32 I get a different result than the actual output. Heres the result I expect to see based on what I got from the website:
expected output = 2147483647
Any idea why this is happening?
Edit:
Forgive me for making it confusing by purposefully attempting to convert 2^31-1.
Using the conversion website I linked to earlier, I changed the input:
String sInput = "GE4DE===";
Expected output:
number = 182
Actual output:
number = 3225650
What you're doing is correct... assuming that the Base32 string comes from Base32-encoding a byte array you get from calling BigInteger.toByteArray().
BigInteger(byte[] val) does not really take an array of arbitrary bytes. It takes the byte[] representation of a BigInteger. Also, it assumes the most-significant byte is in val[0]).
If it's base-32 the X, Y, and Z shouldn't be there. Are you sure it isn't base-36?

Categories