OBX
OBX

Reputation: 6114

Extracting BinaryString as Integer, need suggestions

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

Answers (2)

Am_I_Helpful
Am_I_Helpful

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

  1. first convert the decimal representation of the given number to Binary String(using step 2);
  2. then convert to integer value using step 1;
  3. repeat steps 1 and 2 for the second number; and
  4. finally, perform the XOR operation over them.

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

Czyzby
Czyzby

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

Related Questions