Translating a String containing a binary value to Hex - java

I am trying to translate a String that contains a binary value (e.g. 000010001010011) to it's Hex value.(453)
I've been trying several options, but mostly I get a converted value of each individual character. (0=30 1=31)
I have a function that translates my input to binary code through a non-mathematical way, but through a series of "if, else if" statements. (the values are not calculated, because they are not standard.) The binary code is contained in a variable String "binOutput"
I currently have something like this:
String bin = Integer.toHexString(Integer.parseInt(binOutput));
But this does not work at all.

Try using Integer.parseInt(binOutput, 2) instead of Integer.parseInt(binOutput)

Ted Hopp beat me to it, but here goes anyway:
jcomeau#intrepid:/tmp$ cat test.java; java test 000010001010011
public class test {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("The value of " + args[i] + " is " +
Integer.toHexString(Integer.parseInt(args[i], 2)));
}
}
}
The value of 000010001010011 is 453

Related

Error in creating an array that converts Strings to Doubles and stores them

I'm trying to write a code that given a sequence, (private double[] sequence mentioned earlier in the code defining a sequence), will seperate the strings into an array and then assign the string values into doubles using the Double.parseDouble. The results i get from println are so strange though.
When i enter "2,3,4" as the value for s, the result displays as:
s: 2,3,4
result: [D#1d733e1
This is my code:
...
public Sequence(String s)
{
String[] tokens = s.split(",");
System.out.println("s: " + s);
double[] result = new double[tokens.length];
int i = 0;
for(String token:tokens){
result[i++] = Double.parseDouble(token);
}
System.out.println("result: " + result);
}
}
And i don't know why it's outputting those strange results.
Following this method, i created another method to determine if the values inside the array are equal to each other. This is the code i used for it:
public boolean allEqual()
{double name = sequence[0];
for(int i = 0; i < sequence.length; i++){
if(sequence[i] != name){
return false;
}
name = sequence[i];
}
return true;
And this code keeps saying that the array index is out of bounds: 0 and i feel like it has something to do with my first code.
Any help would be greatly appreciated!
To print an array meaningfully, use the Arrays.toString(result) method. For your code:
System.out.println("result: " + Arrays.toString(result));
This needs to be done because the default toString() implementation of all primitive array objects gives the ugly output you see above. It has some meaning, but in general you will never want to print it out or log it anywhere.
If you use a static code analysis tool like FindBugs, it will warn you about these types of things. http://findbugs.sourceforge.net/
When you say System.out.println("result: " + result); you are asking Java to print out an object, but result is an array which doesn't have a default toString() method, so what it shows is the object's reference, which is not meaningful to the human eye. As mentioned by #Kon you should be more explicit about how you want the data to show up.

Get Portion of String

I need to get the values after "Swap:".
I've already developed a method to get the output from a shell command so I have a string that contains everything you see in the picture but now from the string I want to get ONLY the value after the Swap: How can i do this? These value are variable and can be even all three 0.
Let's say you have the text stored in a String called textContent. Assuming the Swap-line is the last part of your String, then you could do something like this:
int index = textContent.indexOf("Swap:");
index += "Swap:".length();
textContent.subString(index);
Try this:
String[] stringParts = text.substring(text.indexOf("Swap:") + 5).trim().split("( )+");
int[] parts = new int[stringParts.length];
for (int i = 0; i < stringParts.length; i++)
parts[i] = Integer.parseInt(stringParts[i]);
It will fill an integer array will the values after the "Swap" part.
Since you have already stored the output of the shell command, you simply need to do some string manipulation to search and extract the relevant information. The following particular string manipulation methods might be of interest to you: trim(), indexOf(), and substring().
Below is a simple example code on how to extract the value under the total's column using the above String methods:
public class ShellOutput {
public ShellOutput() {
final String extract = "Swap:"; // the keyword to search
String shellOutput = "Swap: 75692 29657 0"; // your shell output
int position = shellOutput.indexOf(extract); // get the position of the Swap: text
if (position != -1) {
String swapLine = shellOutput.substring(position + extract.length()); // remove everything except the swap line
String numbers = swapLine.trim(); // assuming they are spaces, otherwise do some operations to remove tabs if used
int firstSpace = numbers.indexOf(' '); // get the first space or change to a tab character if it is used
String totalNumber = numbers.substring(0, firstSpace); // remove up to the first found after the number
System.out.println("Total = " + totalNumber);
} else {
System.out.println("No '" + extract + "' segment found.");
}
}
public static void main(String[] args) {
new ShellOutput();
}
}
Output: Total = 75692

Reading a data file and processing the information, with two values on each line

I have to produce a program that can read a file I have been given. The file contains 365 lines of data that is supposed to resemble temperature values. The first value on each line is the low temp, and the second is the high temp. From these values, I have to determine the number of days, the lowest of the low temps, highest of the max temps, and then the average of the lows and the average of the highs.
Here is what I have so far. The problem I am having is splitting the two values on each line to deal with them individually so I can turn them into a double so I can do computations on them
import TextIO.*;
public class Temperature {
public static void main(String[] args) {
TextIO.readFile("temperatures.dat");
//double salesTotal; // Total of all sales figures seen so far.
int dayCount, string1, a;
double tempTotal=0;
String dataString; // Number of cities for which data is missing.
dayCount = 0;
while ( ! TextIO.eof() ) { // process one line of data.
dayCount++;
dataString = TextIO.getln(); // Get the rest of the line.
a = dataString.indexOf(" ");
TextIO.put("\n" + a);
}
TextIO.put(dayCount);
}
}
I get the feeling your question comes from a homework assignment so I wont take all the fun out of it but... What you are looking at is most likely a tab represented by\t in java.
You have so far:
dataString = TextIO.getln();
You will then need to separate those 2 numbers, there are several ways to do this but Ill take your lead and use the indexOf method.
String low = dataString.substring(0, dataString.indexOf("\t"));
String high= dataString.substring(dataString.indexOf("\t")+1);
you then need to convert those strings to numbers, but im sure you can figure that out :).
If you ever find yourself wonder what is that character you can do something like this
public static void printStringChars(String str) {
for(int i=0;i<str.length();i++)
System.out.println("(" + str.charAt(i) + ") " + (int)str.charAt(i));
}
Then go look up the number it prints out in an ASCII table such as this one http://www.asciitable.com/

How to treat a string as a variable in java?

Remember playing the game when you indexed each of the words of your name and added it all together to form a secret number? Like aay would be 1+1+25=27
I tried to do the same thing by various methods in java but I failed.Let me share my script first and then tell what all i tried.
class test{
public static void main(String args[]){
int c = 3;
String s = "c";
///now this is what all i tried:
int value1 = (int)(s);
///i tried a cast, but that failed.
String d = "4";
int value2 = Integer.parseInt(d);
///when i try this, it correctly converts the string to an integer.
Integer.parseInt(s);
///but when i try the above, it fails to do the same.
}
}
In this code, I try 2 different methods both of which are working in a similar way that I want to but not exact.
The problem is that it couldn't reorganize that c is a variable that has an integer value.
So, is there any shortcut to do it?
Also, right now the string is only 1 digit long, once the user inputs his or her name, I shall use a for loop to loop all of the letters completely.
If there isn't any shortcut, is the only option left with me is to make an if statement like:
if(letter=a;){
value=1;
}
Or something like that?
thanks for helping!
You can't convert a String directly into an integer, you need to take one character at a time and subtract the value of the char 'a' then add 1 :
public static void main(String[] a) {
String s = "test";
for (char c : s.toLowerCase().toCharArray()){
System.out.println(charToInt(c));
}
}
private static int charToInt(char c){
return c - 'a' + 1;
}
In Java like most other C-eqsue languages, char is a Number type.
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff'
(or 65,535 inclusive).
Just Alphabetic Characters
So all you need to do is convert each character to its equivilent char and you have its ASCII/Unicode value; I won't go into Unicode here, because ASCII maps over Unicode into the correct place.
// this will give you a Zero based int of the
// UPPPERCASE alphabet which starts at `65` and
// ends at `90`.
// See where the lowercases starts and ends?
char c = "My Name".charAt(0) - 65;
// c = 'M' in this case which is 77 - 65 = 12
The ASCII codes are easy to translate.
(source: asciitable.com)
For UPPERCASE letters it is just an exercise of looping through all the chars of a String and getting their code and subtracting 65 to get a 0 based value. It gets a little more complicated to exclude other characters and process lowercase as well, but you get the idea from the table.
Printable Characters
Notice "printable" characters start at 32 and run through 126 which is usually what you just do, is subtract 32 instead of 65 and just convert all "printable" characters to a Zero base.
Example
The following will print out all the "printable" characters.
public class Main
{
public static void main(final String[] args)
{
for (char i = 32; i <= 126; i++)
{
System.out.println(new Character(i));
}
}
}
Solution
Here is a complete solution that will create a secret code, of all the *"printable" characters possible.
public class Main
{
public static void main(final String[] args)
{
int hash = 0;
final String s = args[0];
for (int c = 0; c < s.length(); c++)
{
hash = hash + s.charAt(c) - 32;
}
System.out.printf("Secret code for %s is %d", s, hash);
}
}
the result for my name is
Secret code for Jarrod is 418

CharacterSet to String and Int to Char casting

New to java. Trying to familiarize myself with syntax and overall language structure.
I am trying to mimic this php function in java which just converts all instances of a number to a particular character
for($x=10;$x<=20;$x++){
$string = str_replace($x, chr($x+55), $string);
}
so in php if a string was 1090412 it would be converted to something like A904C.
I am trying to do this in java by using string.replace but I cant for the life of me figure out how to cast the variables properly. I know that I can convert an integer to a character by casting it as (char), but not sure where to go from there. this gives me a compile error expecting a character set.
string=1090412;
for (x = 10; x <= 35; x++) {
string.replace( x, (char) (x + 55));
}
Well, although not the best way to do this, here is a method that works
import java.lang.*;
public class T {
public static void main(String[] args) {
String s = "1090412";
for (int i = 10; i <= 20; i++) {
s = s.replace(Integer.toString(i), "" + (char)(i + 55));
}
System.out.println(s);
}
}
The java.lang.String object has a replace method on it. It is overloaded to take either two char parameters or two CharSequence objects. The "" + (char)(i + 55) is just a quick way to create a CharSequence.

Categories