Having:
byte temp;
and a String which represents a binary number:
String binary = "00100100";
I want to convert this binary number to hex and store it in byte, so: as 00100100 binary equals 24 hex, I want to obtain:
temp = 24;
or
temp = 0x24;
Here's an example
String binary = "00100100";
int value = Integer.parseInt(binary, 2);
System.out.println(value);
System.out.println("0x" + Integer.toHexString(value));
Integer.parserInt(String, int)
Parses the string argument as a signed integer in the radix specified by the second argument.
So it will convert the binary String value to an integer with the specified base.
You can then use the Integer.toHexString(int) method to convert that value to a hex representation, appending the 0x if you really want to.
Related
How can I convert the hexstring into the form of hexint below?
string hexstring = "0x67";
int hexint = 0x67;
Integer#decode can be used to convert hexadecmial string representation into its integer value:
Integer.decode("0x67");
This function automatically detects the correct base and will parse return the int 103 (0x67 = 6*16+7). If you want to manually specify a different base, see my other answer
If you only have a single byte, you can strip of the leading "0x" part and then parse as a base-16 number with Integer#parseInt:
Integer.parseInt("0x67".substring(2), 0x10);
Integer.parseInt("0x67".substring(2), 16);
0x10 is the hexadecimal representation of the decimal number 16.
String hexstring = "67";
int hexint = Integer.parseInt(hexstring, 16);
System.out.println(hexint); // 103 (decimal)
With Integer.parseInt(String s, int radix) you can parse a String to an int.
The radix is the base of that number system, in case of hex-values it is 16.
I have a string as "5F2A" as Hex. I would like to convert it as int 0x5F2A.
String str = "5F2A";
int number = someOperation(str);
And the number should be (with 0x)
0x5F2A
Is it possible?
To rephrase and share what I learnt today
Map<Integer, String> map = new HashMap<>();
map.put(0x5F2A, "somevalue");
System.out.println(map.get(24362));
System.out.println(map.get(0b0101111100101010));
Would give the value somevalue for both.
No transformation required:
System.out.println("0x" + str);
And to turn an arbitrary int into HEX representation:
Integer.toHexString(intNumber);
That should be all you need to get going!
int i = 0x5F2A not really means nothing because in memory, all is in binary, it's only when you print that it matters
String str = "5F2A";
int number = Integer.parseInt(str, 16); //alows to store an int, binary 0101111100101010
System.out.println(number); //24362 (decimal by default)
System.out.println(Integer.toHexString(number)); //5f2a (hexa possible too)
By default, it prints in (binary into) decimal format, but you can print in hexa format, but int i = 0x5F2A means at 100% the same as int i = 24362
See here
Integer.parseInt(/*your String*/, 16);
16 is the radix for hexadecimal.
I was wondering if it's possible to convert a signed Hexadecimal (negative) to its corresponding decimal value.
I assume that you have a hexadecimal value in form of a String.
The method parseInt(String s, int radix) can take a hexadecimal (signed) String and with the proper radix (16) it will parse it to an Integer.
int decimalInt = parseInt(hexaStr, 16);
the solution above only works if you have numbers like -FFAA07BB... if you want the Two's complements you'll have to convert it yourself.
String hex = "F0BDC0";
// First convert the Hex-number into a binary number:
String bin = Integer.toString(Integer.parseInt(hex, 16), 2);
// Now create the complement (make 1's to 0's and vice versa)
String binCompl = bin.replace('0', 'X').replace('1', '0').replace('X', '1');
// Now parse it back to an integer, add 1 and make it negative:
int result = (Integer.parseInt(binCompl, 2) + 1) * -1;
or if you feel like having a one-liner:
int result = (Integer.parseInt(Integer.toString(Integer.parseInt("F0BDC0", 16), 2).replace('0', 'X').replace('1', '0').replace('X', '1'), 2) + 1) * -1;
If the numbers get so big (or small), that an Integer will have an overflow, use Long.toString(...) and Long.parseLong(...) instead.
I have a question about converting String type binary number to bit and write in the txt file.
For example we have String like "0101011" and want to convert to bit type "0101011"
then write in to the file on the disk.
I would like to know is there anyway to covert to string to bit..
i was searching on the web they suggest to use bitarray but i am not sure
thanks
Try this:
int value = Integer.parseInt("0101011", 2); // parse base 2
Then the bit pattern in value will correspond to the binary interpretation of the string "0101011". You can then write value out to a file as a byte (assuming the string is no more than 8 binary digits).
EDIT You could also use Byte.parseByte("0101011", 2);. However, byte values in Java are always signed. If you tried to parse an 8-bit value with the 8th bit set (like "10010110", which is 150 decimal), you would get a NumberFormatException because values above +127 do not fit in a byte. If you don't need to handle bit patterns greater than "01111111", then Byte.parseByte works just as well as Integer.parseInt.
Recall, though, that to write a byte to a file, you use OutputStream.write(int), which takes an int (not byte) value—even though it only writes one byte. Might as well go with an int value to start with.
You can try the below code to avoid overflows of the numbers.
long avoidOverflows = Long.parseLong("11000000000000000000000000000000", 2);
int thisShouldBeANegativeNumber = (int) avoidOverflows;
System.out.println("Currect value : " + avoidOverflows + " -> " + "Int value : " + thisShouldBeANegativeNumber);
you can see the output
Currect value : 3221225472 -> Int value : -1073741824
//Converting String to Bytes
bytes[] cipherText= new String("0101011").getBytes()
//Converting bytes to Bits and Convert to String
StringBuilder sb = new StringBuilder(cipherText.length * Byte.SIZE);
for( int i = 0; i < Byte.SIZE * cipherText .length; i++ )
sb.append((cipherText [i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
//Byte code of input in Stirn form
System.out.println("Bytecode="+sb.toString()); // some binary data
//Convert Byte To characters
String bin = sb.toString();
StringBuilder b = new StringBuilder();
int len = bin.length();
int i = 0;
while (i + 8 <= len) {
char c = convert(bin.substring(i, i+8));
i+=8;
b.append(c);
}
//String format of Binary data
System.out.println(b.toString());
How can I convert an int number from decimal to binary. For example:
int x=10; // radix 10
How can I make another integer has the binary representation of x, such as:
int y=1010; // radix 2
by using c only?
An integer is always stored in binary format internally -- saying that you want to convert int x = 10 base 10 to int y = 1010 base 2 doesn't make sense. Perhaps you want to convert it to a string representing the binary format of the integer, in which case you can use Integer.toBinaryString.
First thing you should understand is that a value is an abstract notion, that is not bounded to any representation. For example, if you have 20 apples, the number of apples will be the same regardless of the representation. So, dec("10") == bin("1010").
The value of an int reffers to this abstract notion of value, and it does not have any form until you with to print it. This means that the notion of base is important only for conversions from string to int and back.
String s = Integer.toBinaryString(10);
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html
Whether it's binary or decimal doesn't really have anything to do with the integer itself. Binary or decimal is a property of a physical representation of the integer, i.e. a String. Thus, the methods you should look at are Integer.toString() and Integer.valueOf() (the versions that take a radix parameter).
BTW, internally, all Java integers are binary, but literals in the source code are decimal (or octal).
Your question is a bit unclear but I'll do my best to try to make sense of it.
How can I make another integer has the binary representation of x such as: int y=1010 radix 2?
From this it looks like you wish to write a binary literal in your source code. Java doesn't support binary integer literals. It only supports decimal, hexadecimal and octal.
You can write your number as a string instead and use Integer.parseInt with the desired radix:
int y = Integer.parseInt("1010", 2);
But you should note that the final result is identical to writing int y = 10;. The integer 10 that was written as a decimal literal in the source code is identical in every way to one which was parsed from the binary string "1010". There is no difference in their internal representation if they are both stored as int.
If you want to convert an existing integer to its binary representation as a string then you can use Integer.toBinaryString as others have already pointed out.
Both integers will have the same interior representation, you can however display as binary via Integer.toBinaryString(i)
Use Integer.toBinaryString()
String y = Integer.toBinaryString(10);
Converting an integer to another base (string representation):
int num = 15;
String fifteen = Integer.toString(num, 2);
// fifteen = "1111"
Converting the string back into an integer
String fifteen = "1111";
int num = Integer.valueOf(fifteen, 2);
// num = 15
This covers the general case for any base. There's no way to explicitly assign an integer as binary (only decimal, octal, and hexadecimal)
int x = 255; // decimal
int y = 0377; // octal (leading zero)
int z = 0xFF; // hex (prepend 0x)