how to convert binary strings longer than 9 characters to integers? - java

I am working on a program where I am trying to take a binary string and convert it to an integer using this piece of code:
int x = Integer.parseInt(arrayList.get(count), 2);
//arrayList is a collection of 30 character binary strings
//count is an incrementing integer used to choose which string to use while inside of a while loop
I have tested this program with strings such as "001010", however with larger strings such as "100000110000010100001111010110" compiles, but terminal output gives me an error:
"# java.lang.NumberFormatException.forInputString(NumberFormatException.java:(line number))
How can I fix this?

You can try java.math.BigInteger.
String bin = "100000110000010100001111010110";
BigInteger bi = new BigInteger(bin, 2);
System.out.println(bi);
Output:
549536726
You can also do it using Long.valueOf(). However, with Long your binary strings can be up to 63 bits long, whereas with BigInteger the length can be of arbitrarily many bits.
String bin = "100000110000010100001111010110";
long biLong = Long.valueOf(bin, 2);
System.out.println(biLong);

Try Long.parseLong method instead of Integer.parseInt

Related

Conversion from hex to binary keeping 8 bits in Java

I need to write in a 8x8 matrix the binary values of 8 hexadecimal numbers (one for row). Those numbers will be at the most 8 bits long. I wrote the following code to convert from hexadecimal to binary:
private String hexToBin (String hex){
int i = Integer.parseInt(hex, 16);
String bin = Integer.toBinaryString(i);
return bin;
}
But I have the problem that values below 0x80 don't need 8 bits to be represented in binary. My question is: is there a function to convert to binary in an 8-bit format (filling the left positions with zeros)? Thanks a lot
My question is: is there a function to convert to binary in an 8-bit format (filling the left positions with zeros)?
No, there isn't. You have to write it yourself.
Here's one simple way. If you know the input is always a single byte, then you could add 256 to the number before calling toBinaryString. That way, the string will be guaranteed to be 9 characters long, and then you can just shave off the first character using substring:
String bin = Integer.toBinaryString(256 + i).substring(1);
Hint: use string concatenation to add the appropriate number of zeros in the appropriate place.
For example:
public String hexToBin(String hex) throws NumberFormatException {
String bin = Integer.toBinaryString(Integer.parseInt(hex, 16));
int len = bin.length();
return len == 8 ? bin : "00000000".substring(len - 8) + bin;
}
(Warning: untested ...)
I've concatenated this way. Thanks!
private String hexToBin (String hex){
int i = Integer.parseInt(hex, 16);
String bin = Integer.toBinaryString(i);
while (bin.length()<8){
bin="0"+bin;
}
return bin;
}

Java binary multiplier of two int/char arrays

currently i am working on a project, that uses Brainpool elliptic curves. For some tests, i need a binary multiplication of two strings.
The strings look something like that:
String a = "00101001";
String b = "11010010";
I convert the two stings into char and integer arrays for the binary multiplication but i dont now how to do it. Can someone help me to handle this? i also tried it with BigInteger but it delets my leading zero's.
Thanks a lot!
Something like the following should work. It creates integers out of the binary string, multiplies the values and the converts it back into a string:
int a = Integer.parseInt("00101001", 2);
int b = Integer.parseInt("11010010", 2);
int x = a*b;
String result = Integer.toBinaryString(x);
Does that work for you?

Compiler error "Incompatible types" on byte literal

I have seen many cases where a byte is declared but where the value from a method like
intToByte or StringToByte is casted to a byte because the programmer is provideing i.e. a hexadecimal- value, an Integer- or a String-value.
I am trying to assign an actual byte value to the variable without any casting or methods to parse, like so:
public class ByteTest {
/**
* This array will be used to hold three characters, together forming a string.
*/
private static byte[] string;
/**
* The main method of the program, where the byte-array is coming to use.
*/
public static void main(String args[]) {
//Construct the array with a limit to three bytes.
string = new byte[3];
/*
* Fill the three bytes with the binary values to create "O", "l" and "e".
*/
string[0] = 01001111;
string[1] = 01101100;
string[2] = 01100101;
//Print out "Ole".
System.out.println(string[0] + string[1] + string[2]);
}
}
But I get the following error in the compiler:
java\ByteTest.java:8: error: incompatible types: possible lossy conversion from int to byte
string[0] = 01001111;
^
java\ByteTest.java:9: error: incompatible types: possible lossy conversion from int to byte
string[1] = 01101100;
^
java\ByteTest.java:10: error: incompatible types: possible lossy conversion from int to byte
string[2] = 01100101;
^
Appearently, what I think of as eight bits, the compiler thinks of as eight integers.
Is there any other solution to this, where I can provide actually bits directly to the variables/array?
Indicate binary
string[0] = 0b01001111;
string[1] = 0b01101100;
string[2] = 0b01100101;
This reminds me of the joke: there are 10 kinds of programmers: those that understand binary and those that do not.
As bytes are signed there still is a problem with 0b1xxxxxxx which would need to be a negative number. In that case use the following trick:
string[2] = 0b11100101 - 256;
string[2] = (byte) 0b11100101; // Or simply cast the int range value.
Also binary is ideal for an underscore usage:
string[2] = 0b0110_0101; // 0x65
And is commented by #BackSlash: bytes are binary data. To interprete them as text they have to be associated with some Charset/encoding.
String s = new String(string, StandardCharsets.US_ASCII);
System.out.println(s);
This converts the bytes, interpreting them as ASCII to the Unicode that String uses (to combine all scripts of the world).
Adding 0 in front of constant number ( like 01101100 ) is interpreted as octal value
What do you need to do to fix this?
The simplest solution which will use the least memory (code and data) is also the simplest.
private static final String string = "Ole";
System.out.println(string);
otherwise you can do this
private static final char[] chars = {
(char) 0b01001111,
(char) 0b01101100,
(char) 0b01100101 };
String s = new String(chars);
System.out.println(s);
Note: characters in Java are 16-bit unsigned char, not 8 bit byte
To get an idea of why the class file is bigger you can dump the class file with
java -c -v -cp target/classes mypackage.MyClass
To start with 01001111 is in octal, not binary. To write a binary number, you need 0b01001111
Numbers don't "remember" how many leading zeros you gave it, and generally speaking, leading zeros are dropped when printed.
The default format for a number is decimal, not binary.
When you add two, or three numbers, you get another number. Assuming you got this to compile it would print something like
288
or whatever the sum of the values are.
BTW it is really confusing to name an int called "string" because this could be assumed to be a String
Assign Actual value :-
String a ="100101";
System.out.println(""+a);
Output :- 100101
Binary to integer conversion and then assign value to string variable :-
String a=""+0b100101
System.out.println(""+a);
Output: 37

NumberFormat error while trying to get binary values from string to integer variable

Hi I am new to Java and any help would be appreciated I am trying to convert an decimal number into binary and then making a left shift on that binary number. But it does not allow me left shift on string and it gives me exception of I try to convert it to integer.
int i = 40700;
iToBinary = Integer.toBinaryString(i);
i = Integer.parseInt(iToBinary);
i=i<<1;
What should be the optimal way to do this. I also need to convert the decimal to binary with the sign magnitude so I don't think a direct function like toBinaryString would work for me. But I would like to know how to do this.
You need additional parameter radix in parseInt method:
see this link for example: How to convert a Binary String to a base 10 integer in Java
Here are java examples for this method:
Examples:
parseInt("0", 10) returns 0
parseInt("473", 10) returns 473
parseInt("+42", 10) returns 42
parseInt("-0", 10) returns 0
parseInt("-FF", 16) returns -255
parseInt("1100110", 2) returns 102
In your case will be :
i = Integer.parseInt(iToBinary, 2);
The binary string you are parsing is to large for an integer. Try the following:
long i = 40700;
iToBinary = Long.toBinaryString(i);
i = Long.parseLong(iToBinary);
i=i<<1;
To solve your exception you can use the overloaded method of Integer.parseInt using two parameters, then you can define the radix.
Change this line:
i = Integer.parseInt(iToBinary);
To this:
i = Integer.parseInt(iToBinary, 2);
This might be of help. Try
int i = 40700;
String iToBinary = Integer.toBinaryString(i<<1);
Long z = Long.parseLong(iToBinary,2);
System.out.println(" i " + z);
The answer we get is 81400

Java parsing long from string

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.

Categories

Resources