How to convert 'unsigned long' to string in java - 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;

Related

How can I use parseInt for a double?

My program receives some input (a String). It is rather possible that the input is in the form of a double, like "1.5". But I would like to convert it to an integer, so I can end up with just a 1.
First, I tried this:
Integer.parseInt(someString);
But it doesn't work - I'm assuming it is because of the dot . that it can't parse it.
So I thought that maybe the Integer class can create an integer from a double. So I decided to create a double and then make it an int, like this:
Integer.parseInt(Double.parseDouble(someString));
But apparently there is
no suitable method found for parseInt(double)
So, what do you suggest? Are there one-liners for this? I thought about making a method that removes the dot and all characters after it... but that doesn't sound very cool.
It is safe to parse any numbers as double, then convert it to another type after. Like this:
// someString = "1.5";
double val = Double.parseDouble(someString); // -> val = 1.5;
int intVal = (int) Math.floor(val); // -> intVal = 1;
Note that with Java 7 (not tested with earlier JVM, but I think it should work too), this will also yield the same result as above :
int intVal = (int) Double.parseDouble(someString);
as converting from a floating value to an int will drop any decimal without rounding.
use casting.
double val = Double.parseDouble(someString);
int intVal = (int) Math.floor(val);
You've got the Double, I assume, with Double.parseDouble. So just use:
int i = (int) Double.parseDouble(someString);
Try,
int no= new Double(string).intValue();
Try this:
1) Parse the string as double
2) cast from double to int
public static void main(String[] args) {
String str = "123.32";
int i = (int) Math.floor(Double.parseDouble(str));
System.out.println(i);
}

convert hexadecimal number string to double-precision number in 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

How to check if bit is set in Hex-String?

shifters...
I've to do something, that twist my mind.
I'm getting a hex value as String (for example: "AFFE") and have to decide, if bit 5 of Byte one is set.
public boolean isBitSet(String hexValue) {
//enter your code here
return "no idea".equals("no idea")
}
Any hints?
Regards,
Boskop
The simplest way is to convert String to int, and use bit arithmetic:
public boolean isBitSet(String hexValue, int bitNumber) {
int val = Integer.valueOf(hexValue, 16);
return (val & (1 << bitNumber)) != 0;
} ^ ^--- int value with only the target bit set to one
|--------- bit-wise "AND"
Assuming that byte one is represented by the last two digits, and the size of the string fixed to 4 characters, then the answer may be:
return (int)hexValue[2] & 1 == 1;
As you an see, you don't need to convert the whole string to binary to evaluate the 5th bit, it is indeed the LSB of the 3rd character.
Now, if the size of the hex string is variable, then you will need something like:
return (int)hexValue[hexValue.Length-2] & 1 == 1;
But as the string can have a length smaller than 2, it would be safer:
return hexValue.Length < 2 ? 0 : (int)hexValue[hexValue.Length-2] & 1 == 1;
The correct answer may vary depending on what you consider to be byte 1 and bit 5.
How about this?
int x = Integer.parseInt(hexValue);
String binaryValue = Integer.toBinaryString(x);
Then you can examine the String to check the particular bits you care about.
Use the BigInteger and it's testBit built-in function
static public boolean getBit(String hex, int bit) {
BigInteger bigInteger = new BigInteger(hex, 16);
return bigInteger.testBit(bit);
}

Any way to avoid results containing "9.223372036854776E18"

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

How to store a large (10 digits) integer?

Which Java data type would be able to store a big numerical value, like 9999999999?
Your concrete example could be stored in long (or java.lang.Long if this is necessary).
If at any point you need bigger numbers, you can try
java.math.BigInteger (if integer), or java.math.BigDecimal (if decimal)
In addition to all the other answers I'd like to note that if you want to write that number as a literal in your Java code, you'll need to append a L or l to tell the compiler that it's a long constant:
long l1 = 9999999999; // this won't compile
long l2 = 9999999999L; // this will work
You can store this in a long. A long can store a value from -9223372036854775808 to 9223372036854775807.
A primitive long or its java.lang.Long wrapper can also store ten digits.
Use BigInt datatype with its implicit operations. The plus point for it is it will not give answers in exponential representation. It will give full length result
Here is an example of addition
BigInteger big1 = new BigInteger("1234567856656567242177779");
BigInteger big2 = new BigInteger("12345565678566567131275737372777569");
BigInteger bigSum = big1.add(big2);
System.out.println(bigSum );
you can use long or double.
You could store by creating an object that hold a string value number to store in an array list.
by example: BigInt objt = new BigInt("999999999999999999999999999999999999999999999999999");
objt is created by the constructor of BigInt class. Inside the class look like.
BigInt{
ArrayList<Integer> myNumber = new ArrayList <Integer>();
public BigInt(){}
public BigInt(String number){ for(int i; i<number.length; i++){ myNumber.add(number.indexOf(i)); } }
}
A wrapper class java.lang.Long can store 10 digit easily.
Long phoneNumber = 1234567890;
It can store more than that also.
Documentation:
public final class Long extends Number implements Comparable<Long> {
/**
* A constant holding the minimum value a {#code long} can
* have, -2<sup>63</sup>.
*/
#Native public static final long MIN_VALUE = 0x8000000000000000L;
/**
* A constant holding the maximum value a {#code long} can
* have, 2<sup>63</sup>-1.
*/
#Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
}
This means it can store values of range 9,223,372,036,854,775,807 to -9,223,372,036,854,775,808.
If you want to take user input then you should take that as string, then convert that into long.
//Take user input using Scanner class
Scanner sc = new Scanner(System.in);
String str = sc.next();
//Convert that to long
long num = Long.parseLong(str);
System.out.println(num); // This is not a string anymore

Categories