convert hexadecimal number string to double-precision number in java - java

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

Related

How to show user defined digits after a decimal

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()

Java format integer limiting width by truncating to the right

I know I could use String.substring or write some extra code, but is there a simple way to achieve this by only using String.format?
For example, I only want the first 6 chars "1234ab" in the result:
int v = 0x1234abcd;
String s = String.format("%06x", v) // gives me 1234abcd
String s = String.format("%06.6x", v) // gives me IllegalformatPrecesionException
The Java Formatter doc said the precision could be used to limit the overall output width, but only to certain data types.
Any ideas? Thanks.
Depending how may hex digits you want to truncate...
You can divide by powers of 16
public static void main(String[] args) throws Exception {
int v = 0x1234abcd;
// This will truncate the 2 right most hex digits
String hexV = Integer.toHexString(v / (int)Math.pow(16, 2));
System.out.println(hexV);
}
Results:
1234ab
Even if you mess up and divide by a power of 16 that exceeds the length of your hex string, the result will just be zero.
Then there's the substring() approach
public static void main(String[] args) throws Exception {
int v = 0x1234abcd;
String hexV = Integer.toHexString(v);
// This will truncate the the 2 most right hex digits
// provided the length is greater than 2
System.out.println(hexV.length() > 2 ? hexV.substring(0, hexV.length() - 2) : hexV);
}
Since you wanted to do this with just the Formatter.
Here's my result.
1234ab
1234abcd
And here's the code.
public class Tester {
public static void main(String[] args) {
int v = 0x1234abcd;
String s = String.format("%6.6s", String.format("%x", v));
System.out.println(s);
s = String.format("%10.10s", String.format("%x", v));
System.out.println(s);
}
}
I convert the hex number to a String, then truncate or left pad the String with the second Formatter.

Java.lang.long cannot be applied to java.lang.string?

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);

How to convert 'unsigned long' to string in java

it is clear that java does not have 'unsigned long' type, while we can use long to store a unsigned data. Then how can I convert it to a String or just print it in a 'unsigned' manner?
You need to use BigInteger unfortunately, or write your own routine.
Here is an Unsigned class which helps with these workarounds
private static final BigInteger BI_2_64 = BigInteger.ONE.shiftLeft(64);
public static String asString(long l) {
return l >= 0 ? String.valueOf(l) : toBigInteger(l).toString();
}
public static BigInteger toBigInteger(long l) {
final BigInteger bi = BigInteger.valueOf(l);
return l >= 0 ? bi : bi.add(BI_2_64);
}
As mentioned in a different question on SO, there is a method for that starting with Java 8:
System.out.println(Long.toUnsignedString(Long.MAX_VALUE)); // 9223372036854775807
System.out.println(Long.toUnsignedString(Long.MIN_VALUE)); // 9223372036854775808
Can you use third-party libraries? Guava's UnsignedLongs.toString(long) does this.
long quot = (number >>> 1) / 5L; // get all digits except last one
long rem = number - quot * 10L; // get last digit with overflow trick
String out = Long.toString(quot) + rem;

Integer.decode(String s)

class Test{
public static void main(String Args[]){
Integer x;
x = Integer.decode("0b111");
System.out.println(x);
}
}
This doesn't work with the prefix 0 for binary and for octal with the prefix 0.
What is the correct way to do it?
Looking at the documentation for Integer.decode, I see no indication that binary should work. Octal should work though, with a prefix of just 0:
System.out.println(Integer.decode("010")); // Prints 8
You could handle a binary indicator of "0b" like this:
int value = text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
Complete sample code showing binary, octal, decimal and hex representations of 15:
public class Test {
public static void main(String[] args) throws Exception {
String[] strings = { "0b1111", "017", "15", "0xf" };
for (String string : strings) {
System.out.println(decode(string)); // 15 every time
}
}
private static int decode(String text) {
return text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
}
}
Integer.decode cannot parse binary, see API. But octal work fine, example:
int i = Integer.decode("011");
As of Java 7, you can use binary literals directly in your code. However, note that these are of type byte, short, int or long (and not String).
int x = 0b111;

Categories