How to convert a binary value to ASCII in JAVA? - java

This is a homework assignment that I can't wrap my head around. I have to do it manually, so I can't use "getBytes()." Also, I have to convert to decimal format first, and then convert the decimal to ASCII (e.g. {0,1,1,0,0,0,1,0} = 98 in decimal format, which is a 'b'). I have arranged the binary code into an array, and want to use a for loop to traverse the array position by position. However, I'm not sure I'm using the correct parameters for the for loop, and am not sure how to divide the code into bits of "8." Another thing, how to I convert the decimal value to ASCII? Should I just list out all the possible letters I know I will get, and then refer to them using an if-else loop? Or could I just convert the decimal to a char? Here is my code so far... (It's a bit messy, sorry)
class Decoder
{
public void findCode(Picture stegoObj)
{
Pixel pixTar = new Pixel(stegoObj,0,0);
Pixel [] pixelArray = stegoObj.getPixels();
int blueVal = 0;
for(int length = 0; length < pixelArray.length; length++)
{
blueVal = pixTar.getBlue();
}
System.out.println(blueVal);
stegoObj.explore();
}
public void decode(int [] binary)
{
int binaryLen = binary.length;
int totVal = 0;
int newVal = 0;
int bitVal = 0;
for(int x = binaryLen - 1; x >= 0; x--)
{
bitVal = binary[x];
int exp = x - (binaryLen - 1);
totVal += (pow(bitVal, exp));
}
System.out.println(totVal);
}
}
public class DecodeImage
{
public static void main(String[] args)
{
Picture stegoObj = new Picture("SecretMessage.bmp");
Decoder deco = new Decoder();
int[] binArray = {0,1,0,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,1,1,1,0,1,1,1,0,1,1,0,1,1,1,1,0,1,1,1,0,0,1,0,0,1,1,0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,1,0,1,0,0,0,0,1,1,0,1,0,0,0,0,1,0,1,0};
//int[] binArray = {0,1,1,0,0,0,1,0};
//deco.findCode(stegoObj);
deco.decode(binArray);
}
}
EDIT:
Okay, so I figured out this much, under the class Decoder, in the decode block, in the for loop:
for(int x = binaryLen - 1; x >= 0; x--)
{
bitVal = binary[x];
preVal = bitVal * base;
totVal += preVal;
base = base * 2;
}

You've got the right idea for decode. I don't see why your code wouldn't work, although I don't see the pow implementation anywhere.
Decimal to ascii is easy, just cast the value to a char:
int v = ...; // decimal value
char c = (char)v; // ascii value

int[] bValue = {1,0,0,0,1,0,1};
int iValue = 0;
// convert binary to decimal
for (int i = 0, pow = bValue.length - 1 ; i < bValue.length ; i++, pow--)
iValue += bValue[i]*Math.pow(2, pow);
// gets the value as a char
char cValue = (char)iValue;
System.out.println("Int value: "+iValue +", Char value : "+cValue);
If you need the whole ASCII table, you may put the values into a Map where the key is the integer value, and the value is the corresponding ASCII entry.

Related

Adding two numbers stored as arrays of chars

I'm trying to write an algorithm which adds two numbers that are stored as chars in two arrays. Unfortunately, it doesn't work. When I try to debug it, I see that the variables a and b get the value -1 which makes no sense. Any idea what might be the problem?
public class rechner2 {
public static void main(String[] args) {
final char[] zahl1 = {1, 2, 3};
final char[] zahl2 = {7, 8, 9};
//Add arrays zahl1 and zahl2.
char [] zwischenarray = add(zahl1, zahl2);
for (int i = 0; i < zwischenarray.length; i++) {
System.out.println(zwischenarray[i]);
}
}
private static char[] add(char[] zahl1, char[] zahl2) {
int len;
if (zahl1.length < zahl2.length) {
len = zahl2.length;
} else {
len = zahl1.length;
}
char[] finalresult = new char [len + 1];
int carryover = 0;
for (int i = 0; i < len; i++) {
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
int c = a + b + carryover;
if (c > 9) {
carryover = 1;
c = c - 10;
} else {
carryover = 0;
}
finalresult[i] = (char)c;
}
if (carryover == 1) {
finalresult[len + 1] = 1;
}
return finalresult;
}
}
in this code I believe 2 bug
instead of char , i guess better to us int
length of the array
here is the code:
public class rechner2 {
public static void main(String[] args) {
int[] zahl1 = {1,2,3};
int[] zahl2 = {7,8,9};
//Add arrays zahl1 and zahl2.
int [] zwischenarray = add(zahl1, zahl2);
for (int i = 0; i < zwischenarray.length; i++) {
System.out.println(zwischenarray[i]);
}
}
private static int[] add(int[] zahl1, int[] zahl2) {
int len;
if (zahl1.length < zahl2.length) {
len = zahl2.length;
} else {
len = zahl1.length;
}
int[] finalresult = new int [len + 1];
int carryover = 0;
for (int i = 0; i <= len-1; i++) {
int a = (zahl1[i]);
int b = (zahl2[i]);
int c = a + b + carryover;
if (c > 9) {
carryover = 1;
c = c - 10;
} else {
carryover = 0;
}
finalresult[i] = c;
}
if (carryover == 1) {
finalresult[len] = 1;
}
return finalresult;
}
}
Your code is conflicted: The numbers / characters in your array are actually integers, not "printable" or "human readable" characters. But, parts of your code are treating them as if they are "printable".
Let's go back decades, and use ASCII for the beginning of this explanation. ASCII has "Printable" and "Nonprintable" characters. The "Nonprintable" characters are known as "Control codes."
Control codes include codes that move the cursor on a display terminal or print head on a printing terminal. They include thing like CR (Carriage Return), LF (Line Feed), HT (Horizontal tab), and BS (Backspace). Others are used by data communications hardware to control the flow of data, or to report status.
Printable characters correspond to what you see on a terminal screen or printout. They include uppercase alphabetic, lower case alphabetic, digits, punctuation, and the space character. They are "human readable."
Look at the list of printable characters in the Wikipedia article. Take 5 as an example. It's represented as '53' in base ten, which corresponds to '35' in base sixteen, or '011 0101' in binary. Note that it is not the same as the binary number five, which would be '0000 0101'.
Java uses 16 bit Unicode, not ASCII, for its char type. The Java compiler allows arithmetic to be done on char data, as if it was the same as short.
These lines in your code expect your char variables and constants are printable characters:
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
In addition, that you specified zwischenarray as char tells the compiler to handle the contents as printable characters in this line:
System.out.println(zwischenarray[i]);
But, the rest of your code treats your char data as integer data types.
You have a bug in this line: finalresult[len + 1] = 1;. After that bug is fixed, how do you fix the rest of your code? There are different ways, and which is best depends on your intention.
For demonstration purpose, try this: Replace the following
int a = Character.getNumericValue(zahl1[i]);
int b = Character.getNumericValue(zahl2[i]);
int c = a + b + carryover;
with
int c = zahl1[i] + zahl2 [i] + carryover;
Also, put a cast in your output line:
System.out.println((short)zwischenarray[i]);
And run it. That will demonstrate you can do arithmetic on Java char data.
Now, remove the (short) cast in output line, and change all occurrences of char to short (or int). Your program still works.
This is because of the way you entered the values for zahl1 and zahl2. Your source code consists of printable characters and white space. By omitting the single quotes, you told the compiler to convert the values to binary integers. For example, your source code 9 became binary 0000 1001 in the runtime code. If you wanted your 9 to remain as a printable character, you needed to enclose it in single quote marks: '9' .
By enclosing all the values in zahl1 and zahl2 in single quote marks, the use of Character.getNumericValue is appropriate. But, you would still need the (short) or (int) cast in your System.out. line to see your output.
Character.getNumericValue is returning -1 because the values passed are outside of the range it was designed to work with.
Here are two ways to convert a base 10 digit represented as a binary integer to the equivalent printable character:
finalresult[i] = (char) (c + '0');
But, my preference is for this:
final String digit = "0123456789";
finalresult[i] = digit.charAt (c);

Convert Binary to Hexadecimal in Java without methods

I am currently a beginner in programming and I am trying to write a program in java to convert binary in hexadecimal numbers.
I know that the program will have to divide the number in groups of 4 and convert them to hexadecimal.
Ex: 11101111 (b2) --> E + F --- EF
However, since I used ints to do the conversion of the numbers, I'm stuck when I need to print a letter because it is a String.
Can someone point me to the right way? What am I doing wrong? I've also tried another version with an auxiliary array to store each group of 4 digits but I can't manage to insert a proper dimension to the array.
Unfortunately I am not allowed to use any function other than Scanner and Math, the method lenght and charAt and the basic stuff. I can't modify the public static line either.
EDIT: So after your inputs and so many tries, I managed to get this code. However it gives me an error if I insert too many numbers, eg: 0111011010101111. I've tried to change int to double but that didn't fix the problem.
import java.util.Scanner;
public class Bin2HexString {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
System.out.println("Valor?");
int vlr = keyb.nextInt();
String num = "";
int aux = vlr;
// Hexadecimal numbers
String arr[] = {"0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D", "E", "F"};
String bits[] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
String letters = "";
//Divide in groups of 4
int r;
for (; aux > 0; ) {
r = aux % 10000;
aux = aux / 10000;
num = "" + r;
for (;num.length() < 4;) { //add missing zeros
String zero = "0";
num = zero + num;
}
int charint = 0,bitint = 0;
for (int i = 0; i < arr.length;i++) {
String aux2 = bits[i];
String aux3 = arr[i];
for (int j = 0; j < num.length();j++) { // compare each group with arr[i]
char charvl = num.charAt(j);
char bitsvl = aux2.charAt(j);
charint = ((int) (charvl)-'0');
bitint = ((int) (bitsvl) - '0');
if (bitint != charint)
break;
}
if (bitint == charint)
letters = aux3 + "" + letters;
}
}
System.out.println(letters);
}
}
Having thought about this for a while to determine the most effective and useful way to do this is to write methods which convert a string from any base between 2 and 16 to an int and back to a string again.
This way you have useful methods for other things. And note that they methods can be easily changed and names to simply hard code the desired radix into the method to limit it to binary and hex methods.
The indexOf utility method was written to avoid using the builtin String method.
final static String hex = "0123456789ABCDEF";
static int stringToInt(String str, int radix) {
if (radix < 2 || radix > 16) {
System.out.println("Base must be between 2 and 16 inclusive");
return -1;
}
int v = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int idx = indexOf(hex, c);
if (idx < 0 || idx > radix) {
System.out.println("Illegal character in string (" + c + ")");
}
v = v * radix + idx;
}
return v;
}
static String intToBase(int v, int radix) {
if (radix < 2 || radix > 16) {
System.out.println("Base must be between 2 and 16 inclusive");
return null;
}
String s = "";
while (v > 0) {
int idx = v % radix;
s = hex.charAt(idx) + s;
v /= radix;
}
return s;
}
static int indexOf(String str, char c) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
return i;
}
}
return -1;
}
And here is an example of their use.
// generate some test data
Random r = new Random(23);
String[] bitStrings =
r.ints(20, 20, 4000).mapToObj(Integer::toBinaryString).toArray(
String[]::new);
for (String bitstr : bitStrings) {
int v = baseToInt(bitstr, 2);
String hex = intToBase(v, 16);
System.out.printf("%12s = %s%n", bitstr, hex);
}
Which prints the following:
101110000011 = B83
111001111100 = E7C
10001110111 = 477
100110001111 = 98F
111001010 = 1CA
111001001111 = E4F
111000011010 = E1A
100001010010 = 852
11011001101 = 6CD
111010010111 = E97
Just some quick notes:
First this is wrong:
//Divide in groups of 4
for (; aux > 0; ) {
r = aux % 10000;
aux = aux / 10000;
Not at all what you want to do. Try it by hand and see what happens. Take a simple number that you know the answer to, and try it. You won't get the right answer. A good test is 17, which is 11 hex.
Try this instead: convert directly to the base you want. Hex is base 16 (its radix is 16), so you use 16 instead.
//Divide in groups of 4
for (; aux > 0; ) {
r = aux % 16;
aux = aux / 16;
Try those numbers with the test case, which is 17, and see what you get. That will get you much closer.
I'm assuming by "without methods" in the title, you are attempting to write your own integer parsing method instead of using Scanner.nextInt(int radix). In that case, my first advice would be work with a string instead of an integer - you'll be able to handle larger numbers and you can simply make an array of substrings (length 4) to convert to letters.
So, if you use the string approach - first scan in a string, not an int. Then I'd recommend a hash table with the 4-bit strings as keys and the hexadecimal equivalents as values. That should make calculation quite fast.
e.g.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class HashMapBin2Hex
{
public static void main(String[] args)
{
//Read the string in
Scanner sc = new Scanner(System.in);
System.out.println("Binary number?");
String bin = sc.nextLine();
//Pad the bitstring with leading zeros to make a multiple of four
String zeros = "";
int i;
if (bin.length() % 4 != 0)
{
for (i = 0; i < 4 - (bin.length() % 4); i++)
{
zeros += "0";
}
}
bin = zeros + bin;
//Split the padded string into 4-bit chunks
String[] chunks = new String[bin.length() / 4];
for (i = 0; (i * 4) < bin.length() - 1; i++)
{
chunks[i] = bin.substring(i * 4, (i * 4) + 4);
}
//Convert the chunks to hexadecimal
String hex = "";
Map<String, String> bin2hex = new HashMap<>();
bin2hex.put("0000", "0");
bin2hex.put("0001", "1");
bin2hex.put("0010", "2");
bin2hex.put("0011", "3");
bin2hex.put("0100", "4");
bin2hex.put("0101", "5");
bin2hex.put("0110", "6");
bin2hex.put("0111", "7");
bin2hex.put("1000", "8");
bin2hex.put("1001", "9");
bin2hex.put("1010", "A");
bin2hex.put("1011", "B");
bin2hex.put("1100", "C");
bin2hex.put("1101", "D");
bin2hex.put("1110", "E");
bin2hex.put("1111", "F");
for (String s : chunks)
{
hex += bin2hex.get(s);
}
System.out.println("Hexadecimal: " + hex);
sc.close();
}
}
Further iterations could have some error checking to prevent catastrophic failure in the case of characters other than 0 or 1.
And of course, if you're fine with the other way (builtins), the following is far easier and more robust (ie will throw an exception if the string contains anything other than 0s and 1s):
import java.util.Scanner;
public class BuiltinBin2Hex
{
public static void main(String[] args)
{
//Read the binary number in
Scanner sc = new Scanner(System.in);
System.out.println("Binary number?");
int bin = sc.nextInt(2);
//And print as hexadecimal
System.out.println("Hexadecimal: " + Integer.toString(bin, 16));
sc.close();
}
}

How to go through a number (float) and get every number separately with an int. Java

Is there any good way to search through a floats first four numbers and return every number separately with int[]?
Example: the float 23,51 becomes the integer array, array[0]=2, array[1]=3, array[2]=5 and last array[3]=1
My code:
public void printNumber(float number){
String string = String.valueOf(number);
while(!numbers.isEmpty()){
numbers.remove(0);
}
for(int i = 0; i < string.length(); i++) {
int j = Character.digit(string.charAt(i), 10);
this.number = new Number(j);
numbers.add(this.number);
System.out.println("digit: " + j);
}
}
I should mention that Number is a class that only returns a different picture based on the number the constructor is given and ofcourse the number itself.
numbers is an ArrayList
Convert float to String using fixed-point format, then go through its characters one-by-one, and ignore the decimal point.
If the number could also be negative, you need to pay attention to the sign in the String output:
float v = 23.51F;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
char[] d = df.format(v).toCharArray();
int count = 0;
for (int i = 0 ; i != d.length ; i++) {
if (Character.isDigit(d[i])) {
count++;
}
}
int[] res = new int[count];
int pos = 0;
for (int i = 0 ; i != d.length ; i++) {
if (Character.isDigit(d[i])) {
res[pos++] = Character.digit(d[i], 10);
}
}
Demo.
Important: Be aware that floats are inherently imprecise, so you may get a "stray" digit or two. For example, your example produces
[2 3 5 1 0 0 0 0 2 3]
with 2 and 3 at the end.
You can convert the float to String with 4 decimal places using String.format method, and then get each character to int array
float floatValue = 12.34567f;
String str = String.format("%.4f", floatValue);
// remove the minus, dot, or comma (used in some countries)
str = str.replaceAll("[-|.|,]", "");
int [] nums = new int[str.length()];
for (int i=0; i<str.length(); i++) {
nums [i] = str.charAt(i) - '0';
}
Here is DEMO
As for the code last line, decimal value of '0' char (which is 48) is subtracted from a decimal value of digit char, and the result is integer value of that digit (as specified in below table):
Java 8 flavored solution:
float number = -7.54f;
int[] digits = String.format("%.3f", number)
.chars()
.filter(Character::isDigit)
.limit(4L)
.map(Character::getNumericValue)
.toArray();
System.out.println(Arrays.toString(digits)); //=> [7, 5, 4, 0]
Use the static method Float.toString() to convert your float to a String.
Then go through each char and use Integer.parseInt() to get back to an int.
public void printNumber(float number){
String string = Float.toString(number);
for(int i = 0; i < string.length(); i++) {
int j = Integer.parseInt(string.charAt(i));
this.number = new Number(j);
numbers.add(this.number);
System.out.println("digit: " + j);
}
}
Another option
public static void main(String[] args) {
float number = 23.51f;
String strNumber = String.valueOf(number).replaceAll("\\D", "");
int[] arrNumber = new int[strNumber.length()];
for (int pos = 0; pos < strNumber.length(); ++pos) {
arrNumber[pos] = Integer.valueOf(String.valueOf(strNumber.charAt(pos)));
System.out.println(arrNumber[pos]);
}
}

Converting String binary to integer

How can I do this without using multiplication, division or mod?
I come with the solution but it needs multiplication.
public StringBToInt(String b) {
int value = 0;
for(int z = 0; z < b.length(); z++) {
value = value * 2 + (int)b.charAt(i) - 48;
}
}
EDIT: SORRY! Only 3 java API are allowed. length(), charAt(), and equals()
Without multiplication, use bitwise shift operator:
public StringBToInt(String b) {
int value = 0;
for(int z = 0; z < b.length(); z++) {
if(b.charAt(z) == '1'){
shift = b.length()-z-1;
value += (1 << shift);
}
}
}
Use the Integer.valueOf(String, int) method:
Integer.valueOf('10101',2)
Try to use Integer.parseInt(..) like this:
int value = Integer.parseInt(b, 2);
Ofcourse b is a binary String.
You can use the method Integer.parseInt to do this.
String binary = "101010"
int value = Integer.parseInt(binary, 2);
The '2' in Integer.parseInt means to parse the String in base 2.

Binary Int Array to ASCII Equivalent in Java

I searched around here for awhile and nothing seems to help me with my assignment. I'm trying to convert an int array that has binary code in it manually, do the decimal conversion and then cast it as a char to get the ascii equivalent. I have something started, but when I print it out, I get -591207182 as the message, which obviously isn't correct. I have my program down below. I'm fairly novice at writing and understanding Java, so the most efficient and easy to understand route would be much appreciated.
class DecodeMessage
{
public void getBinary(Picture secretImage)
{
Pixel pixelObject = null;
Color pixelColor = null;
int [] binaryInt = new int[secretImage.getWidth()];
int x = 0;
int redValue = 0;
while(redValue < 2)
{
Pixel pixelTarget = new Pixel(secretImage,x,0);
pixelColor = pixelTarget.getColor();
redValue = pixelColor.getRed();
binaryInt[x] = redValue;
x++;
}
}
public void decodeBinary(int [] binary)
{
int binaryLen = binary.length;
long totVal = 0;
int newVal = 0;
int bitVal = 0;
long preVal = 0;
long base = 2;
for(int x = binaryLen - 1; x >= 0; x--)
{
bitVal = binary[x];
preVal = bitVal * base;
totVal += preVal;
base = base * 2;
}
System.out.println(totVal);
}
}
public class DecodeMessageTester
{
public static void main(String[] args)
{
Picture pictureObj = new Picture("SecretMessage.bmp");
pictureObj.explore();
DecodeMessage decode = new DecodeMessage();
decode.getBinary(pictureObj);
int[] bitArray = {0,1,1,0,0,0,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1};
decode.decodeBinary(bitArray);
}
}
Your problem is that you're trying to squeeze all 48 bits into one int. However, as http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html states, an int in Java can only hold 32 bits, so your numbers overflow. Try changing base, preVal and totVal to long, which can hold 64 bits.
Of course, if you need more than 64 bits (or 63 actually because the last bit is the sign bit), you will not be able to use a primitive number datatype to hold that.

Categories

Resources