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.
See more on this question at Stackoverflow