I want to convert binary string to dec.
public class HelloWorld{
public static void main(String []args){
System.out.println(Integer.parseInt("000011011111110111000001110000111110", 2));
}
}
I get error:
java.lang.NumberFormatException: For input string: "000011011111110111000001110000111110".
How to fix it?
Short solution - Integers simply don't go that high. That's not an int.
ParseInt() documentation mentions, you recieve a string and a radix, and get back the result of the convertion. However, integers are 4 bytes = 32 bits, and thus range from -(2^31) to 2^31-1, and your number - 11011111110111000001110000111110, is in fact 32 bits long - which means, it's bigger than the maximal value. Thus, the function throws this NumberFormatException - this is not a valid value for an int.
If you'd like to fix it, I'd use a ByteBuffer, like described here:
ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN); // if you want little-endian
int result = buffer.getShort(); // use with a bigInteger instead. you could use any of the bytebuffer functions described in the link :)
You can use BigInteger class and store the number as long:
BigInteger bigInt=new BigInteger("000011011111110111000001110000111110");
long a=bigInt.longValue();
The value you are going to store is too big for int and does not fall inside the range the type int can hold(-(2^31) to 2^31-1).So it throws NumberFormatException.long is a suitable option here.
You can use Long.parseLong for the string in your question, still you may find a limit in that also, so you have to implement different logic.
You can have a method that convert the binary string to integer.
public static long binaryToInteger(String binaryString) {
char[] chars = binaryString.toCharArray();
long resultInt = 0;
int placeHolder = 0;
for (int i=chars.length-1; i>=0; i--) {
if (chars[i]=='1') {
resultInt += Math.pow(2,placeHolder);
}
placeHolder++;
}
return resultInt;
}
Related
I do not want the answer, I would just like guidance and for someone to point to why my code is not performing as expected
My task is to flip an integer into binary, reformat the binary to a 32 bit number and then return the unsigned integer. So far my code successfully makes the conversions and flips the bits however I am getting a NumberFormatException when I attempt to parse the string value into a long that ill convert to an unsigned integer.
What is the issue with my code? What have I got misconstrued here? I know there are loads of solutions to this problem online but I prefer working things out my own way?
Could I please get some guidance? Thank you
public class flippingBits {
public static void main(String[] args) {
//change the number to bits
long bits = Long.parseLong(Long.toBinaryString(9));
String tempBits = String.valueOf(bits);
//reformat so that you get 32 bits
tempBits = String.format("%" + (32) + "s", tempBits).replace(" ", "0");
//flip the bits
tempBits = tempBits.replace("1", "5");
tempBits = tempBits.replace("0", "1");
tempBits = tempBits.replace("5", "0");
//Pass this to a long data type so that you can then eventually convert the new bits
// to an unsigned integer
long backToNum = Long.parseLong(tempBits);
}
}
You're directly parsing the bits into a long value instead of converting the bits into an equivalent value.
You need to use the following method (Long.parseUnsignedLong()):
long backToNum = Long.parseUnsignedLong(tempBits, 2); //output: 4294967286
The second argument represents radix:
To interpret a number written in a particular representation, it is necessary to know the radix or base of that representation. This allows the number to be converted into a real value.
See the representation of each radix (From Wikipedia):
I'm trying to return a part of a number, like so:
int foo = 123456789;
System.out.println( foo[0-3] ); //123
I'd also like to get a slice of the number for different indexes, from 2 to 5 for example. In Python, it is pretty straightforward but for some reason it's not so easy to do the same in Java.
foo is a number, not an array, so you can't do a slice on it. You need to convert it to String first and do a substring (= char array slice):
int foo = 123456789;
String slice = String.valueOf(num).substring(0, 3);
System.out.println(slice); // prints 123
If you need to use it as a number again, you need to convert it back to int:
int converted = Integer.parseInt(slice);
You could convert the int to String, substring it and parse it to an integer again:
int foo = 123456789;
String foorStr = Integer.toString(foo);
String fooSubstr = foo.substring(0, 3); //the last index is exclusive
int fooParted = Integer.parseInt(fooSubstr);
int v=123456;
System.out.println(String.valueOf(v).substring(1,3));
There is already a method parseInt that lends itself to this. It takes a String value, starting location, ending location, and a radix. You can make it a little easier as follows:
System.out.println(getSubNumber(123456789, 2,6));
public static int getSubNumber(int value, int start, int end) {
return Integer.parseInt(Integer.toString(value), start, end, 10);
}
prints
3456
or forego the method and just use Integer.parseInt directly. There is an equivalent Long.parseLong for long types.
I have this question that has completely stumped me.
I have to create a variable that equals Integer.MAX_VALUE... (in Java)
// The answer must contain balanced parentesis
public class Exercise{
public static void main(String [] arg){
[???]
assert (Integer.MAX_VALUE==i);
}
}
The challenge is that the source code cannot contain the words "Integer", "Float", "Double" or any digits (0 - 9).
Here's a succinct method:
int ONE = "x".length();
int i = -ONE >>> ONE; //unsigned shift
This works because the max integer value in binary is all ones, except the top (sign) bit, which is zero. But -1 in twos compliment binary is all ones, so by bit shifting -1 one bit to the right, you get the max value.
11111111111111111111111111111111 // -1 in twos compliment
01111111111111111111111111111111 // max int (2147483647)
As others have said.
int i = Integer.MAX_VALUE;
is what you want.
Integer.MAX_VALUE, is a "static constant" inside of the "wrapper class" Integer that is simply the max value. Many classes have static constants in them that are helpful.
Here's a solution:
int ONE = "X".length();
int max = ONE;
while (max < max + ONE) {
max = max + ONE;
}
or lots of variants.
(The trick you were missing is how to "create" an integer value without using a numeric literal or a number wrapper class. Once you have created ONE, the rest is simple ...)
A bit late, but here goes:
int two = "xx".length();
int thirtyone = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".length();
System.out.println(Math.pow(two, thirtyone)-1);
How did I go? :p
I do like that bitshift one though...
The issue is that the answer cannot contain: "Integer", "Float", "Double", and digits (0 - 9)
There are other things in Java which can be represented as an Integer, for example a char:
char aCharacter = 'a';
int asInt = (int) aCharacter;
System.out.println(asInt); //Output: 97
You can also add chars together in this manner:
char aCharacter = 'a';
char anotherCharacter = 'b';
int sumOfCharacters = aCharacter + anotherCharacter;
System.out.println(sumOfCharacters); //Output: 195
With this information, you should be able to work out how to get to 2147483647on your own.
OK, so an Integer can only take certain values. This is from MIN_VALUE to MAX_VALUE where the minimum value is negative.
If you increase an integer past this upper bound the value will wrap around and become the lowest value possible. e.g. MAX_VALUE+1 = MIN_VALUE.
Equally, if you decrease an integer past the lower bound it will wrap around and become the largest possible value. e.g. MIN_VALUE-1 = MAX_VALUE.
Therefore a simple program that instantiates an int, decrements it until it wraps around and returns that value should give you the same value as Integer.MAX_VALUE
public static void main(String [] arg) {
int i = -1
while (i<0) {
i--;
}
System.out.println(i);
}
I'm currently trying to parse some long values stored as Strings in java, the problem I have is this:
String test = "fffff8000261e000"
long number = Long.parseLong(test, 16);
This throws a NumberFormatException:
java.lang.NumberFormatException: For input string: "fffff8000261e000"
However, if I knock the first 'f' off the string, it parses it fine.
I'm guessing this is because the number is large and what I'd normally do is put an 'L' on the end of the long to fix that problem. I can't however work out the best way of doing that when parsing a long from a string.
Can anyone offer any advice?
Thanks
There's two different ways of answering your question, depending on exactly what sort of behavior you're really looking for.
Answer #1: As other people have pointed out, your string (interpreted as a positive hexadecimal integer) is too big for the Java long type. So if you really need (positive) integers that big, then you'll need to use a different type, perhaps java.math.BigInteger, which also has a constructor taking a String and a radix.
Answer #2: I wonder, though, if your string represents the "raw" bytes of the long. In your example it would represent a negative number. If that's the case, then Java's built-in long parser doesn't handle values where the high bit is set (i.e. where the first digit of a 16 digit string is greater than 7).
If you're in case #2, then here is one (pretty inefficient) way of handling it:
String test = "fffff8000261e000";
long number = new java.math.BigInteger(test, 16).longValue();
which produces the value -8796053053440. (If your string is more than 16 hex digits long, it would silently drop any higher bits.)
If efficiency is a concern, you could write your own bit-twiddling routine that takes the hex digits off the end of the string two at a time, perhaps building a byte array, then converting to long. Some similar code is here:
How to convert a Java Long to byte[] for Cassandra?
The primitive long variable can hold values in the range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 inclusive.
The calculation shows that fffff8000261e000 hexademical is 18,446,735,277,656,498,176 decimal, which is obviously out of bounds. Instead, fffff8000261e000 hexademical is 1,152,912,708,553,793,536 decimal, which is as obviously within bounds.
As everybody here proposed, use BigInteger to account for such cases. For example, BigInteger bi = new BigInteger("fffff8000261e000", 16); will solve your problem. Also, new java.math.BigInteger("fffff8000261e000", 16).toString() will yield 18446735277656498176 exactly.
The number you are parsing is too large to fit in a java Long. Adding an L wouldn't help. If Long had been an unsigned data type, it would have fit.
One way to cope is to divide the string in two parts and then use bit shift when adding them together:
String s= "fffff8000261e000";
long number;
long n1, n2;
if (s.length() < 16) {
number = Long.parseLong(s, 16);
}
else {
String s1 = s.substring(0, 1);
String s2 = s.substring(1, s.length());
n1=Long.parseLong(s1, 16) << (4 * s2.length());
n2= Long.parseLong(s2, 16);
number = (Long.parseLong(s1, 16) << (4 * s2.length())) + Long.parseLong(s2, 16);
System.out.println( Long.toHexString(n1));
System.out.println( Long.toHexString(n2));
System.out.println( Long.toHexString(number));
}
Note:
If the number is bigger than Long.MAX_VALUE the resulting long will be a negative value, but the bit pattern will match the input.
How can I examine each digit (System.out.println() each digit, for instance) of a BigInteger in Java? Is there any other way other than converting it to a string?
Straight-forward code prints digits from the last towards the first:
private static void printDigits(BigInteger num) {
BigInteger[] resultAndRemainder;
do {
resultAndRemainder = num.divideAndRemainder(BigInteger.TEN);
System.out.println(Math.abs(resultAndRemainder[1].intValue()));
num = resultAndRemainder[0];
} while (num.compareTo(BigInteger.ZERO) != 0);
}
The BigInteger API docs do not appear to provide any functionality as such. Moreover, the numbers are quite likely not represented in base 10 (since it would be quite inefficient). So it is most likely that the only way to inspect the decimal digits of a BigInteger is to look at its string representation.
You could of course use basic math to calculate each digit. Especially the method divideAndRemainder might help here. But I doubt, that this is more efficient than converting to a String and examing the characters. BigInteger math is more expensive than plain int or long math after all.
I think the only way you could do it is converting it into a String and verify each char. Here is an example:
BigInteger bigInteger = new BigInteger("123");
String bigIntegerValue = bigInteger.toString();
for(int i = 0; i < bigIntegerValue.length(); i++) {
System.out.println(bigIntegerValue.charAt(i));
}
Maybe you can try to examine each bit in your biginteger using BitSet like this,
BitSet bitSet = BitSet.valueOf(bigInteger.toByteArray());
It seems pretty simple what you need to do get each digit of a number.
create a loop that tracks if you number is greater then ten and then preform a mod 10 operation on it and then divide by ten.
while (num >10)
{
System.out.println(num%10);
num = num/10;
}