How can i convert a binary fraction or a decimal fraction into hex in Java?
What is the algorithm to do that?
for example i want (11.110)2 be converted into (3.C)16
and which data type do I need to hold the hex fraction ?
plz help.
Thanks.
This answer is not meant to be a complete guide on how to make a fully working program that converts from one radix to another, but it mentions most of the steps you'd have to do if you want to use the built-in methods that are available.
There are no built-in methods for converting floating-point numbers, but there are built-in methods for converting integers from/to any radix between 2-36. If you only need to convert between binary and hexadecimal and nothing else, you could also do it manually (see below the line further down), but I recommend using these methods otherwise.
If you remove the radix point . from the number (in its String-representation), you get a whole number, but keep track of how many digits were to the right of the radix point.
Here are three ways to convert a whole number from a String with any radix:
Integer.parseInt(String val, int radix) will convert to int.
Long.parseLong(String val, int radix) will convert to long.
new BigInteger(String val, int radix) will convert to BigInteger.
You should then convert the number to a double or BigDecimal, and make sure you get the radix point back in place, by dividing by the correct number. For instance, you can turn (1234)6 into (12.34)6 by dividing it by 6².
Now you are halfway done, and basically go backwards to convert the number back to a String (but with some other radix).
At the step where you want to convert from int/long/BigInteger to a String, use toString:
Integer.toString(int val, int radix) will convert from int.
Long.toString(long val, int radix) will convert from long.
val.toString(int radix) will convert from BigInteger.
Remember to insert the radix point again, and you're done.
To convert from binary to hex manually, you do the same as you would do if they were whole numbers, with few differences.
Divide the binary number into sets of 4 consecutive digits, starting at the radix point, going both left and right. Add leading/trailing zeros as needed. The rest is as explained in the link.
For instance: 101011.011 is divided into 0010 1011 . 0110 which becomes 2B.6 after converting each set to hexadecimal.
Related
[InputParam1:Decimal Number in String format(for Eg:30),
InputParam2:Integer to denote number of repeating 0's to append(for Eg:6)]
For converting a number from Decimal to Binary and pad digits to its front I need to perform the following steps:
Step1: BigInteger binary=new BigInteger(InputParam1,2);
-->This works when I define a BigInt with a base 16 (which I just tried when base2 failed) but not with a base 2 like above.
It throws a numberformat exception.
Step 2: String pad=StringUtils.repeat("0",InputParam2);
(to repeat 0 'InputParam2' number of times)
-->This works fine
Step 3: Need to append pad in front of binary(from Step1)
For a BigInteger, I'm not able to get something similar to .append.
So I'm trying to a)convert this BigInteger number to String and b)append pad c)convert back to BigInteger (this step I'm not able to get without creating a new BigInteger)
Any pointers on Step1 and Step3-c would be helpful please.
#1 - You haven't said what value you're passing in InputParam1, but my guess is that you're passing in something other than a string containing only '0' in '1' characters. The 'radix' parameter to the constructor tells the code how to interpret the string you're giving it. This works fine for me:
BigInteger binary=new BigInteger("1000",2);
System.out.println(binary);
How you construct the number has nothing to do with how you're eventually going to want to represent or display that number. The key idea here is that the representation of a number (hex, decimal, binary) has nothing to do with the number itself, just like leading zeros don't affect the value of number. 1111 binary, f hex, and 15 decimal are all the same number. If you pass the three of these into BigDecimal's constructor with a radix of 2, 16 and 10 respectively, you'll end up with EXACTLY the same thing in each case. The object will lose any notion of what kind of representation you used to set it to its initial value.
#3 - There is no concept of a number (int, BigInteger, etc.) with zero padding at the front, just as there's no notion of which base/radix you might use to represent a number visually. You can think about it conceptually, but that's just a way of displaying the number. It has nothing to do with the number itself.
I hadn't tried it before, but it seems there's no super simple way to format a binary value in Java with leading 0s, like there is for decimal and hex, since String.format() doesn't give a format specifier for binary. Per this StackOverflow post How to get 0-padded binary representation of an integer in java?, this seems to be about the best way to go, having converted the most accepted answer to work with BigInteger:
String str = String.format("%16s", binary.toString(2)).replace(' ', '0');
So here's all of my sample code, with output:
BigInteger binary=new BigInteger("1000",2);
System.out.println(binary);
String str = String.format("%16s", binary.toString(2)).replace(' ', '0');
System.out.println(str);
Output:
8
0000000000001000
From javadoc, I understand that Java, by default, has int data type as a 32-bit signed two's complement integer, which has a minimum value of -2^31 and a maximum value of 2^31-1.
If that is the case, why does this:
System.out.println(Integer.parseInt("1111", 2));
give a value of 15 instead of -1(2's complement signed number).
You've made an assumption that, because integers are represented internally using two's complement, Integer.parseInt with a radix of 2 (binary) also takes numbers in that form. That assumption was incorrect.
Your best bet with stuff like this is to read the documentation. There's no mention of two's complement. It does however say:
the first character may be an ASCII minus sign '-' ('\u002D') to
indicate a negative value
So if you want to parse values represented using two's complement, you will have to write a function which converts the binary number to the absolute value, then appends a minus if necessary.
According to the javadoc of java.lang.Integer class parseInt(String s, int radix) method does the following;
Parses the string argument as a signed integer in the radix specified
by the second argument. The characters in the string must all be
digits of the specified radix.
When you run;
System.out.println(Integer.parseInt("1111", 2));
You are telling the method to take "1111" as a string and convert it to an int value with a base of 2(your radix), eventually it sums to 15 in binary.
Your input "1111" is actually a shortcut to this string "0000 0000 0000 1111", which represent 15.
For the method Integer.parseInt(binaryString, 2), if your binaryString's first char is not '-', then it means parse an unsigned int.
Why are this two methods using two different approaches while processing binary numbers? String which represents negative binary number in Integer.parseInt(String s, 2) method should start with - character, but Integer.toBinaryString(int i) returns string with additional 1 ahead. So, this code
Integer.parseInt(Integer.toBinaryString(-1), 2);
throws java.lang.NumberFormatException. What is the reason of such behavior?
This is by design; Integer.toBinaryString
Returns a string representation of the integer argument as an unsigned integer in base 2.
(emphasis added).
I.e., toBinaryString provides a way to format an integer as the common two's complement representation, which is the way most processors actually store signed integers internally.
Integer::parseInt(String,int) is expecting a string and so it is looking for the - symbol in negative number. Whereas the Integer::toBinaryString(int) is for giving you the binary equivalent of your input. In Binary, negative numbers are represented by 2's Compliment.
I am currently dealing with numbers with different bases. I am using the function Long.parseLong to convert a number from base int to its decimal value:
Long.parseLong("A", 16) to convert A which is a hexadecimal to its decimal value 10. I then use Long.toString(10, 16) to convert it back to A.
The problem now is that one of the entries in the problem set is "AAAAAAAAAAAAAAAAAAA" and when I use the Long.parseLong(); function, it returns an error because the size of the conversion can't fit to a Long. I tried to use Float, but I'm afraid that there is no Float.parseFloat(String, int) with the int as its radix.
Is there an alternative which I can use?
BigInteger also doesn't have any parse function with the radix.
Any help will be much appreciated.
BigInteger has a constructor, which does radix conversion for you:
BigInteger num = new BigInteger("AAAAAAAAAAAAAAAAAAA", 16);
If you wish to convert back to hexadecimal, you can use toString:
String hex = num.toString(16);
I have an sequence of 30 or so hexa decimal values 0x01, 0x02...
My question is how can i store these values in Java. I do not know if it matters to convert it into String and store it. But thats what i am not looking for. I just want to store the hexa decimal as constant data. Please also consider the contents representing the Hex-Decimal form and if/what happens to it ?
Hexadecimal is just a format to display numbers, just like decimal, binary or octal. Numbers are just numbers - hexadecimal is not a property of the numbers themselves, it's only a way to display numbers.
Writing the numbers as 0x01, 0x02, etc. in your source code is exactly the same as writing them in decimal 1, 2 etc.
So, you can store the numbers like you would store any other numbers - for example as an array of ints.
You should store them as Integers using the Integer.valueOf(String s, int radix) method.
In your case, the radix is 16.
Just store them in an integer (if it fits within the value range) ... when displaying them, convert it as hex.