I am trying to write a program for converting positive binary inputs into hex.
Why am i getting this errors while compiling my binary to hex converter..
BinToHex.java:45: toHexString(long) in java.lang.Long cannot be applied to (java.lang.String)
hexOutput = Long.toHexString(tempDecString);
^
1 error
my code..
class BinToHex
import java.io.*;
public class BinToHex {
double tempDec,fractionpart;
long longofintpart,templongDec;
String inpu ="1001.01";
String hexOutput,intpart,tempDecString,hex = null;
static int i = 1;
public void convertbintohex() {
if (inpu.contains(".")) {
int placesAfterPoint = inpu.length() - inpu.indexOf(".") - 1;//every thing
long numerator = Long.parseLong(inpu.replace(".", ""), 2);//goes
double decimalOfInput = ((double) numerator) / (1L << placesAfterPoint);//alright till here
while (true) {
tempDec = decimalOfInput * 16;
if ((int)tempDec == tempDec) {
tempDecString = String.valueOf(tempDec);
templongDec = Long.valueOf(tempDecString).longValue();
hexOutput = hexOutput+Long.toHexString(templongDec);
break;
} else {
intpart = String.valueOf((long)tempDec);
longofintpart = Long.valueOf(intpart).longValue();
if(i==1){
hex=Long.toHexString(longofintpart);
hexOutput = hex + ".";
i=i+1;
}else{
hexOutput = hexOutput + hex;
}
fractionpart = tempDec-(int)tempDec;
decimalOfInput = fractionpart;
}
}
} else {
// this part is ok
tempDecString = String.valueOf(Integer.parseInt(inpu, 2));
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(tempDecString);
}
System.out.println(hexOutput);
}
}
class Test,,
public class Test{
public static void main(String args[]){
BinToHex i = new BinToHex();
i.convertbintohex();
}
}
plz help.
thanks.
Well yes, look at the signature of Long.toHexString:
public static String toHexString(long i)
You're trying to pass in a string. Given that it's meant to convert a long into a string, it's not at all clear what you would expect this to do, but that's why you're getting the error - which is exactly what the compiler is telling you. (Compiler errors are sometimes obscure, but in this case they're really not...)
You seem to be doing far more conversions than you ought to be. You're doing some hex conversion yourself by the looks of it, and then some conversion to decimal... why are you doing anything with a decimal representation if you're converting binary to hex?
It's not really clear what your expected input/output is given that you've got a floating binary point in there, but I would just parse from binary to a byte[] and convert that byte array to hex using a 3rd party library... unless you know that the values will only ever be in the range of long, in which case it's fine to use Long.parseLong and Long.toHexString, but those should be all you need. Get rid of any conversions to/from decimal.
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(tempDecString);
you are passing the string as paramter to the static method. Change it in
hexOutput = Long.toHexString(templongDec);
Related
I am trying to figure out how to show the correct number of digits after a decimal, based off a number passed into the method.
public static double chopDecimal(double value, int place)
{
int chopped;
//???
return chopped;
}
So if the value passed is 123.456789 and the place is 2, it should show 123.45.
The print statement is in another method.
System.out.println("***MyMath ChopDecimal Test***");
//Chop Decimal Test 1
if (MyMath.chopDecimal(123.456789, 2) == 123.45)
{
System.out.println("Chop Decimal Test 1 Passed");
}
else
{
System.out.printf("Chop Decimal Test 1 Failed. Your answer: %f Correct Answer: 123.45\n",
MyMath.chopDecimal(123.456789, 2));
}
//Chop Decimal Test 2
if (MyMath.chopDecimal(.98765, 4) == .9876)
{
System.out.println("Chop Decimal Test 2 Passed");
}
else
{
System.out.printf("Chop Decimal Test 2 Failed. Your answer: %f Correct Answer: .9876\n",
MyMath.chopDecimal(.98765, 4));
}
This is possible using java.text.NumberFormat, although when you wish to convert to String for 'showing' purposes.
To match your example though, I've converted it babck to a double:
public static double chopDecimal(double value, int place)
{
String chopped = NumberFormat.getInstance().setMaximumFractionDigits( place ).format( value );
return Double.valueOf( chopped );
}
I suggest you to use the java Rounding Mode.
Simple example:
public static void main(String[] args) {
System.out.println(chopDecimal(123.456789, 2));
}
public static String chopDecimal(double value, int place)
{
// Parameter is the pattern
DecimalFormat format = new DecimalFormat("0.00");
format.setRoundingMode(RoundingMode.HALF_UP);
return format.format(value);
}
This question is duplicated:
How to round a number to n decimal places in Java
Reference:
Oracle Documentation
All of the answers above are pretty great, but if this for something you need to be able to explain, I wrote the segment of code below with all pretty basic tools of programming. Study this process below, it's not always about the solution, more so about can you come up with a solution. Always keep that in mind when solving any problem. There is always time later to improve your solution.
public static void main(String[] args) {
chopDecimal(123.456789,2);
}
public static double chopDecimal(double value, int place)
{
String valToStr = Double.toString(value);
int decimal=0;
for(int i = 0; i < valToStr.length(); i++)
{
if(valToStr.charAt(i) == '.')
{
decimal = valToStr.indexOf(valToStr.charAt(i));
System.out.println(decimal);
break;
}
}
String newNum = valToStr.substring(0,(++decimal+place));
System.out.println(newNum);
double chopped = Double.parseDouble(newNum);
return chopped;
}
}
Let me know if you have any questions.
You can use BigDecimal and setScale:
double chopped = BigDecimal
.valueOf(value)
.setScale(place, RoundingMode.DOWN)
.doubleValue()
how to cast String with period and comma to int, like
String a "9.000,00"
int b = Integer.parseInt(a);
when I run this code, I get an error message : Exception in thread "main" java.lang.NumberFormatException: For input string: "9.000,00"
If you want to get as result 900000 then simply remove all , and . and parse it with for instance with Integer.parseInt or Long.parseLong or maybe even better use BigInteger if number can be large.
String a = "9.000,00";
BigInteger bn = new BigInteger(a.replaceAll("[.,]", ""));
System.out.println(bn);
Output: 900000
But if you want to parse 9.000,00 into 9000 (where ,00 part is decimal fraction) then you can use NumberFormat with Locale.GERMANY which uses form similar to your input: 123.456,78
String a = "9.000,00";
NumberFormat format = NumberFormat.getInstance(Locale.GERMANY);
Number number = format.parse(a);
double value = number.doubleValue();
//or if you want int
int intValue = number.intValue();
System.out.println(value);
System.out.println(intValue);
Output:
9000.0
9000
final String a = "9.000,00";
final NumberFormat format = NumberFormat.getInstance(Locale.GERMAN); // Use German locale for number formats
final Number number = format.parse(a); // Parse the number
int i = number.intValue(); // Get the integer value
Reference
To do that, you need to use java.text.NumberFormat and NumberFormat.getInstance(Locale.FRANCE) (or another compatible Locale)
import java.text.NumberFormat;
import java.util.Locale;
class Test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
Number number = format.parse(a);
double d = number.doubleValue();
int c = (int) Math.floor(d);
System.out.println(c);
}
}
prints 9000 as you want ( and now is an int ) !
If I print every intermediate step :
import java.text.NumberFormat;
import java.util.*;
class test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
System.out.println(a); // prints 9000,00
Number number = format.parse(a);
System.out.println(number); // prints 9000
double d = number.doubleValue();
System.out.println(d); // prints 9000.0
int c = (int) Math.floor(d);
System.out.println(c); // prints 9000
}
}
so if Okem you want 9000,00 as you're saying in your comment, you just need
a = a.replaceAll("\\.", "");
System.out.println(a);
which gives you an output of 9000,00
I hope that helps.
Try this -
String a = "9.000,00";
a = a.replace(",","");
a = a.replace(".","");
int b = Integer.parseInt(a);
I think DecimalFormat.parse is the Java 7 API way to go:
String a = "9.000,00";
DecimalFormat foo = new DecimalFormat();
Number bar = foo.parse(a, new ParsePosition(0));
After that, you go and be happy with the Number you just got.
If you want the answer to be 900000 (it doesn't make sense to me, but I'm replying to your question) and put that into an int go with:
int b = Integer.parseInt(a.replaceAll(",","").replaceAll("\\.",""));
as already outlined in the comments.
The goal is to convert a String to int in java.
My declarations:
String [] dataIn = new String[100];
int [] binVals = new int[100];
int i;
String toBinary;
I first convert a hex string to a binary string.
static String hexToBin(String s) {
return new BigInteger(s,16).toString(2);
}
.....
.....
toBinary = hexToBin(dataIn[i]);
try{
int temp = Integer.parseInt(toBinary);
binVals[i] = temp;
System.out.println(temp);
} catch (NumberFormatException ex){
System.out.println("Not gonna work");
}
toBinary is a String value of 32 bits i.e. 00011100...01
I printed the result to the console to make sure it is valid for an integer conversion. Yet, using Integer.parseInt(toBinary); still throws the exception. What am I missing here?
Updated
According to what you guys said, I now no longer receive an exception, but when I convert the binary String into an integer, it seems to become a decimal integer.
if (i % 2 == 0)
{
toBinary = hexToBin(dataIn[i]);
System.out.println("Binary in String: " + toBinary);
try{
int temp = Integer.parseInt(toBinary, 2);
binVals[i] = temp;
System.out.println("binVals[i] in int" + binVals[i]);
} catch (NumberFormatException ex){
System.out.println("Not gonna work");
}
//System.out.println(temp);
} else {
System.out.println("This should be a timestamp: " + dataIn[i]);
}
Output:
Binary in String: 1001010101010101010101010100000
binVals[i] in int1252698784
This should be a timestamp: 2068a40
The problem is that Integer.parseInt without a radix will interpret the string as a decimal number, not binary. Most such "binary" strings will represent numbers that are over the maximum integer possible, a little over 2 billion, e.g. 111,000,101,010,001.
Pass in a radix of 2 (binary) to Integer.parseInt:
int temp = Integer.parseInt(toBinary, 2);
However, if the first "bit" is set, then the represented number will be over Integer.MAX_VALUE, and then only Long.parseLong will work.
Try Integer.parseInt(toBinary, 2);. the 2 specifies that the string is in binary (base 2)
Edit: for your new issue, the problem is that Java will by default print integers as decimal, so you need to turn your (decimal) integer back into a binary string. You can use Integer.toBinaryString(int i) for this.
For parsing and formatting integers you should consider using BigInteger.
Converting to String in any radix use BigInteger.toString(int radix).
For parsing use new BigInteger(String s, int radix).
how can we convert hexadecimal number string to double-precision number in java ?
in matlab it's simple :
>> hex2num('c0399999a0000000')
ans =
-25.6000
but could I do the same things in java also ?
I tried parseInt() but this number is not integer.
I think you want Double.longBitsToDouble, like this:
public class Test {
public static void main(String[] args) {
String hex = "c0399999a0000000";
long longHex = parseUnsignedHex(hex);
double d = Double.longBitsToDouble(longHex);
System.out.println(d);
}
public static long parseUnsignedHex(String text) {
if (text.length() == 16) {
return (parseUnsignedHex(text.substring(0, 1)) << 60)
| parseUnsignedHex(text.substring(1));
}
return Long.parseLong(text, 16);
}
}
(The fact that long is signed in Java makes this more awkward than you'd really want, but hey...)
First make a long, and then call longBitsToDouble
I'm making a program that turns a large number into a string, and then adds the characters of that string up. It works fine, my only problem is that instead of having it as a normal number, Java converts my number into standard form, which makes it hard to parse the string. Are there any solutions to this?
public static void main(String ags[]) {
long nq = (long) Math.pow(2l, 1000l);
long result = 0;
String tempQuestion = Double.toString(nq);
System.out.println(tempQuestion);
String question = tempQuestion.substring(0, tempQuestion.length() - 2);
for (int count = 0; count < question.length(); count++) {
String stringResult = question.substring(count, count + 1);
result += Double.parseDouble(stringResult);
}
System.out.println(result);
Other answers are correct, you could use a java.text.NumberFormat (JavaDoc) to format your output. Using printfis also an option for formatting, similar to NumberFormat. But I see something else here. It looks like you mixed up your data types: In
nq = (long) Math.pow(2l, 1000l);
you are already truncating the double return value from Math to a long. Then you should use long as data type instead of double for the conversion. So use Long.toString(long), this will not add any exponent output.
Use Long.toString(nq) instead of Double.toString(nq); in your code.
As you say: "NumberFormat". The class.
BigInteger is easy to use and you don't risk precision problems with it. (In this particular instance I don't think there is a precision problem, because Math.pow(2, 1001) % 100000 returns the correct last 5 digits, but for bigger numbers eventually you will lose information.) Here's how you can use BigInteger:
groovy:000> b = new BigInteger(2L)
===> 2
groovy:000> b = b.pow(1001)
===> 214301721437253464189685009812000362112280962341106721488750077674070210224
98722449863967576313917162551893458351062936503742905713846280871969155149397149
60786913554964846197084214921012474228375590836430609294996716388253479753511833
1087892154125829142392955373084335320859663305248773674411336138752
groovy:000> ((b + "").toList().collect {new Integer(it)}).inject(0) {sum, n -> sum + n}
===> 1319
Here's the same thing in Java:
public class Example
{
public static void main(String[] args)
{
int sum = 0;
for (char ch : new java.math.BigInteger("2").pow(1001).toString().toCharArray()) {
sum += Character.digit(ch, 10);
}
System.out.println(sum);
}
}
Link to the javadoc for NumberFormat: Javadoc
just replace last line:
System.out.println(result);
with
System.out.printf("%d", result);