Convert Binary String to Binary - java

How do I convert a String written as Binary, to binary (in byte array)?
If I have a String:
String binary = "0000"
I want the binary data to be 0000.
below is what happens when I set the binary to a byte array (which in turn returns 48, which is ASCII)
Binary String: 0000
Binary Byte array: 48
Binary Byte array: 48
Binary Byte array: 48
Binary Byte array: 48
I'm not good at explaining so hopefully the above example was enough to tell you what I want.
EDIT: This is to set the data into a binary file.

Use this:
System.out.println(Integer.toBinaryString(Integer.parseInt("000",2))); // gives 0
System.out.println(Integer.toBinaryString(Integer.parseInt("010",2))); // gives 10
System.out.println(Integer.toBinaryString(Integer.parseInt("100",2))); // gives 100

Maybe you want this:
int i = Integer.valueOf(binary, 2); // ie base 2
This call expects the input to be a string of 0 and 1 chars.
Then if you want an array of bytes:
byte[] bytes = new ByteBuffer().putInt(i).compact().array();

Convert into Decimal from Binary
System.out.println(new BigInteger("1010",2).toString()); // 10 decimal
Convert into Binary/Octal/Hex from Decimal
You can use BigInteger#toString(radix) method to get value in any radix.
System.out.println(new BigInteger("10").toString(2)); // 1010 binary
System.out.println(new BigInteger("10").toString(8)); // 12 octal
System.out.println(new BigInteger("10").toString(16)); // a hexadecimal
Let me explain you a bit more how it works with different base
(10)10 = (1010)2
(10)10 = (12)8
(10)10 = (a)16

JBBP framework has in utils a special method to convert a string contains a binary defined data into byte array
byte [] converted = JBBPUtils.str2bin("00000000");

Related

Putting my 32 bits into a 4 bytearray

I am putting different binary numbers into a byte array. One of the numbers are: 10001101010010010000000000001000 this number is giving me a NumberFormatException on the line where I try to parse it, obviously because it's too big. See code below where string is the binary number.
int number = Integer.parseInt(string, 2);
ByteBuffer bytes = ByteBuffer.allocate(4).putInt(number);
byte[] byteInstruction = bytes.array();
What I want is to put the numbers in my byte array but as they are 32-bit numbers I don't want to take up more than 4 bytes in my array. When I use long to parse it works but then I take up 8 spaces in my byte array.
long number = Long.parseLong(string, 2);
ByteBuffer bytes = ByteBuffer.allocate(8).putLong(number);
byte[] byteInstruction = bytes.array();
If I print out the array later I get this:
[0, 0, 0, 0, -115, 73, 0, 8]
where we can see that there are 4 spots free. How can I solve this? How did I mess up?
All help is appreciated.
Your input string "10001101010010010000000000001000" represents value that is too big for signed Integer. Integer.MAX_VALUE = 2147483647 and the input string you've passed has a value of 2370371592.
The Integer.parseInt does not interpret the leading 1 at position 32 from right as sign. If you would like parse a negative value it would have to be preceded with - sign.
See this answer for more through explanation.
If you expect the input "10001101010010010000000000001000" to in fact mean "-0001101010010010000000000001000" just replace the first character with +/- depending on the value of 32 bit from right.
Alternatively if you would like to treat the binary string in Two's complement compatible way you can use approach from this answer:
int msb = Integer.parseInt("1000110101001001", 2);
int lsb = Integer.parseInt("0000000000001000", 2);
int result = msb<<16 | lsb;

Wrong Decimal Representation of Hexadecimal Value

I have a small data set in HexaDecimal Representation -
byte[] bb = new byte[] { (byte)0x7D, (byte)0x44, (byte)0xCC };
To understand how the values are coming in Decimal Representation, I did the following -
Log.i("DECIMAL VALUE of 7D>>", buf[i] + "");
Log.i("DECIMAL VALUE of 44>>", buf[i+1] + "");
Log.i("DECIMAL VALUE of CC>>", buf[i+2] + "");
And what it printed was -
DECIMAL VALUE of 7D>> 125
DECIMAL VALUE of 44>> 68
DECIMAL VALUE of CC>> -52
Looking into the site -
http://hextodecimal.com/index.php?hex=CC
The Decimal Representation of byte CC is 204.
In my application I am getting Index Out Of Bounds Exception just because index at -52 doesn't exist in the bounds.
So how is this byte coming negative and what is the clear solution.
Bytes in Java are signed i.e. they range from -128 to 127. If you want to represent the number 204, use an int.
int[] bb = new int[] { 0x7D, 0x44, 0xCC };
If you really want to store the data as bytes, you can convert it to unsigned where you use it to index in an array.
yourArray[bb[1] && 0xFF]
See the following question: How to Convert Int to Unsigned Byte and Back

applying 2's complement in hex string in java

i have hex value 03E7 which is string in type.i need to apply 2s compliment in this string.and the resultant hex value should be in string format.i first converted it to binary then converted .is there is any simple method?
Negative numbers are the 2's complement of positive numbers and vice versa, so I suppose you could parse your string into an int, multiply by -1, and then parse it back into the resulting hex string.
int intVal = Integer.parseInt("03E7", 16);
String twosComplement = Integer.toHexString((-1 * intVal));

How does BigInteger interpret the bytes from a string?

Im working on a program that is an implementation of the RSA encryption algorithm, just as a personal exercise, its not guarding anyone's information or anything. I am trying to understand how a plaintext passage is being interpreted numerically, allowing it to be encrypted. I understand that most UTF-8 characters end up only using 1 byte of space, and not the 2 bytes one might think, but thats about it. Heres my code:
BigInteger ONE = new BigInteger("1");
SecureRandom rand = new SecureRandom();
BigInteger d, e, n;
BigInteger p = BigInteger.probablePrime(128, rand);
BigInteger q = BigInteger.probablePrime(128, rand);
BigInteger phi = (p.subtract(ONE)).multiply(q.subtract(ONE));
n = p.multiply(q);
e = new BigInteger("65537");
d = e.modInverse(phi);
String string = "test";
BigInteger plainText = new BigInteger(string.getBytes("UTF-8"));
BigInteger cipherText = plainText.modPow(e, n);
BigInteger originalMessage = cipherText.modPow(d, n);
String decrypted = new String(originalMessage.toByteArray(),"UTF-8");
System.out.println("original: " + string);
System.out.println("decrypted: " + decrypted);
System.out.println(plainText);
System.out.println(cipherText);
System.out.println(originalMessage);
System.out.println(string.getBytes("UTF-8"));
byte byteArray[] = string.getBytes("UTF-8");
for(byte littleByte:byteArray){
System.out.println(littleByte);
}
It outputs:
original: test
decrypted: test
1952805748
16521882695662254558772281277528769227027759103787217998376216650996467552436
1952805748
[B#60d70b42
116
101
115
116
Maybe more specifically i am wondering about this line:
BigInteger plainText = new BigInteger(string.getBytes("UTF-8"));
Does each letter of "test" have a value, and they are literraly added together here? Like say t=1,e=2,s=3,t=1 for example, if you get the bytes from that string, do you end up with 7 or are the values just put together like 1231? And why does
BigInteger plainText = new BigInteger(string.getBytes("UTF-8")); output 1952805748
I am trying to understand how a plaintext passage is being interpreted numerically, allowing it to be encrypted.
It really boils down to understanding what this line does:
BigInteger plainText = new BigInteger(string.getBytes("UTF-8"));
Lets break it down.
We start with a String (string). A Java string is a sequence of characters represented as Unicode code points (encoded in UCS-16 ...).
The getBytes("UTF-8") then encodes the characters as a sequence of bytes, and returns them in a newly allocated byte array.
The BigInteger(byte[]) constructor interprets that byte array as a number. As the javadoc says:
Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger. The input array is
assumed to be in big-endian byte-order: the most significant byte is
in the zeroth element.
The method that is being used here is not giving an intrisically meaningful number, just one that corresponds to the byte-encoded string. And going from the byte array to the number is simply treating the bytes as a bit sequence that represents an integer in 2's complement form ... which is the most common representation for integers on modern hardware.
The key thing is that the transformation from the text to the (unencrypted) BigInteger is lossless and reversible. Any other transformation with those properties could be used.
References:
The Wikipedia page on 2's Complement representation
The Wikipedia page on the UTF-8 text encoding scheme
javadoc BigInteger(byte[])
javadoc String.getBytes(String)
Im still not quite understanding how the the UTF-8 values for each character in "test", 116,101,115,116 respectively come together to form 1952805748?
Convert the numbers 116,101,115,116 to hex.
Convert the number 1952805748 to hex
Compare them
See the pattern?
The answer is in the output, "test" is encoded into array of 4 bytes [116, 101, 115, 116]. This is then interperted by BigInteger as binary integer representation. The value can be calculated this way
value = (116 << 24) + (101 << 16) + (115 << 8) + 116;

Java Hexa Complement

How does one obtain the complementary hexadecimal value for a given input ?
This could be a bit more generic, i.e. having an array of X possible values, how do you convert a random array like arr[x] --> arr[arr.length - arr.indexOf(x)].
Please ignore the syntax.
The following code snippet will find 16 complement of hexadecimal number:
BigInteger subtrahend = new BigInteger("2D", 16);
// input, you can take input from user and use after validation
char[] array = new char[subtrahend.toString(16).length()];
// construct a character array of the given length
Arrays.fill(array, 'F');
// fill the array by F, look at the first source there the FF is subtracted by 2D
BigInteger minuend = new BigInteger(new String(array), 16);
// construct FFF... Biginteger of that length
BigInteger difference = minuend.subtract(subtrahend);
// calculate minus
BigInteger result = difference.add(BigInteger.ONE);
// add one to it
System.out.println(result.toString(16));
// print it in hex format
Hope this will help you. Thank you.
Source:
Binary and Hexadecimal Arithmetic
Digital Principles and Logic Design
First find the 15's complement of the given input by subtracting it from the number FF... which is of the same length of the input. Then add 1 to it.

Categories

Resources