Reputation: 6114
PS: I tried searching many existing questions here on Stackoverflow, however it only added chaos to my query!
10101
11100
11010
00101
Consider this as a sample Input, which I need to read as BinaryString
one by one! Then I need to represent them as an Integer
.
Obviously int x = 20
initializes x
as a decimal Integer,
and I read from other questions that int y = 0b101
initializes y
as a binary Integer
.
Now, The question is: If I have a binaryString, how do I cast it into an int
like with a preceding 0b
. My objectives following this is to perform bit level OR
and XOR
operations.
ie from the above input, I need to do 10101 ^ 11100
Let me know if this is the right way to approach a problem like this, Thanks!
Upvotes: 0
Views: 56
Reputation: 19168
If I have understood your question correctly, you want to know how to represent Binary Strings as Integer.
Well, you can perform this task for conversion of Binary String to Integer:
String input = "0b1001";
String temp = input.substring(2);
int foo = Integer.parseInt(temp, 2);
Alternately, to switch back :
String temp = Integer.toBinaryString(foo);
from the above input, I need to do 10101 ^ 11100.
You can achieve the same using proper decimal representation of integer. If you want to re-invent the wheel, then
But, I don't see how it'll be performing/calculating differently. It'd still be stored as the same integer. It is just that you will get extra satisfaction(on your part) that the number was read as an integer and then converted to Binary representation of that number.
Upvotes: 1
Reputation: 3139
Try Integer.parseInt(String s, int radix)
. It will throw an exception if the binary string is invalid, so you might want to validate the input.
String binary = "10001";
int asInt = Integer.parseInt(binary, 2); // 17
int
supports ^
(bitwise XOR) operator. All you have to do is convert your binary strings to int
variables and perform the desired operations.
Upvotes: 1