I'm looking for a method that converts binary numbers to hexa decimals (JAVA). Problem is that it can't be done with a predefined method and I just don't know how to do it. I've tried a few things but it throws me off that hexa decimals include chars.
thanks in advance!
It's really a crappy question. You should explain what you have come up with and show the code you've tried so far.
So here's a binary number:
0101111010110010
Split it into groups of four bits (a bit is a binary digit, i.e. 1 or 0):
0101 1110 1011 0010
Now the funny thing is that each group of four bits has a maximum value of....
1111 = 8 + 4 + 2 + 1 = 15
Does that ring a bell? Here are the 'digits' in hexadecimal:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A, B, C, D, E, F
What's the maximum value of a single hexadecimal digit?
15
So this means you can simply translate each group of four bits into a hexadecimal digit:
0101 1110 1011 0010
4+1 8+4+2 8+2+1 2
5 14 11 2
5 E B 2
5EB2
For your requirement first of all you have to convert binary no into decimal and then into hexadecimal. So please try this program it works as per your requirement :
import java.util.Scanner;
public class BinaryToHexa
{
public static void main(String args[])
{
int binnum, rem;
String hexdecnum="";
int decnum=0;
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Binary Number : ");
binnum = scan.nextInt();
// converting the number in decimal format
int i=0;
while(binnum>0)
{
rem = binnum%10;
binnum=binnum/10;
decnum = decnum + (int)(rem*Math.pow(2,i));
i++;
}
// converting the number in hexadecimal format
while(decnum>0)
{
rem = decnum%16;
hexdecnum = hex[rem] + hexdecnum;
decnum = decnum/16;
}
System.out.print("Equivalent Hexadecimal Value is :\n");
System.out.print(hexdecnum);
}
}
If you have any doubt please let me know.
Thanks...
What is the exact issue or problem here?
Use Integer.toHexString(num) to convert
Try this function from my library out. You do not do any calculation with this function. Only string compare, and you can convert as much binary to hexadecimal as you like. As long as the limitation on how long a string can be.
public static String binhexZ(String input)
{
String map = "0000,0,0001,1,0010,2,0011,3,0100,4,0101,5,0110,6,0111,7,1000,8,1001,9,1010,A,1011,B,1100,C,1101,D,1110,E,1111,F";
String output = "";
int i = 0;
while (input.length() % 4 != 0){
input = "0" + input;
}
while (i < input.length()){
output += map.charAt(map.indexOf(input.substring(i, i + 4)) + 5);
i = i + 4;
}
output = output.replaceAll("^0+", "");
output = output.length() < 1? "0" : output;
return output;
}
Related
Example:
a = "100"
b = "11"
Return a + b = “111”.
its done by parsing int but when two strings are more then int size then it will not working.
i tried with long :
long a1=Long.parseLong(a,2);
long b1=Long.parseLong(b,2);
long sum=a1+b1;
String ans=Long.toBinaryString(sum);
is there any methods for double??
To exceed the long size you will need BigInteger.
public void test() {
String a = "100";
String b = "11";
BigInteger bA = new BigInteger(a, 2);
BigInteger bB = new BigInteger(b, 2);
System.out.println(a + " + " + b + " = " + bA.add(bB).toString(2));
}
This does not help with double though.
For double you can try this:
double number = 2.2;
Long.toBinaryString(Double.doubleToLongBits(number));
https://stackoverflow.com/a/8272792/6049590
Copied and modified from above Source
public double ConvertToDouble(string str){
long v = 0;
for (int i = str.Length - 1; i >= 0; i--) v = (v << 1) + (str[i] - '0');
return = BitConverter.ToDouble(BitConverter.GetBytes(v), 0);
}
https://social.msdn.microsoft.com/Forums/vstudio/en-US/0ff76c9a-8d8c-46f3-94cc-420f719a14e4/how-to-convert-floatdoubleulong-into-binaryotcalhex-string?forum=netfxbcl
Copied and modified from above Source
public string ConvertToString(double value){
string s = String.Empty;
foreach (byte b in BitConverter.GetBytes(value))
{
s += Convert.ToString(b,2).PadLeft(8,'0'); // for hex. For binary, use 2 and 8. For octal, use 8 and 3
}
return s;
}
And now the last one:
double c = ConvertToDouble(a) + ConvertToDouble(b);
string bitString = ConvertToString(c);
string bitString should be your expected result.
For adding then converting String again :
public String XXX()
{
int a = Double.parseDouble("100.0");
int b = Double.parseDouble("11.0");
return (a + b) + "";
}
For adding then returning :
public double XXX()
{
int a = Double.parseDouble("100.0");
int b = Double.parseDouble("11.0");
return (a + b);
}
Have a nice day!
If the strings are too long to fit any of the standard types and you don't want to use BigInteger, then you can do it the old-fashioned way using the same algorithm you use when adding two numbers by hand, on paper.
For example, if you have "110" and "11", you would write:
110
+ 11
----
Then you start from the right and move left, adding the digits. Your first partial result is "1", in the right-hand column:
110
+ 11
----
1
Next, "1" and "1" is "0", with a carry of "1". So you write the "0" and note that you have a carry. Your partial result is "01", with the carry.
In the third column you add the "1" and the carry, again giving you "0" with a carry. Your partial result is "001" and the carry. In the fourth column you add the carry, giving you the final result, "1001".
To do that in code, the easiest thing is to pad the shorter number with "0" on the left so that it's the same length as the longer number. So in the example above I would have turned the "11" into "011". Then write a loop that will process the strings from right to left. I'm not a Java programmer, but you should be able to get the idea from this pseudocode.
number1 = "110"
number2 = "011"
result = ""
carry = 0
for i = length(number1) downto 0
digit1 = number1[i].ToInt()
digit2 = number2[i].ToInt()
sum = digit1 + digit2 + carry
if (sum % 2) == 0
result = result + "0"
else
result = result + "1"
carry = (result > 1)
end for
if (carry = 1)
result = result + "1"
That's the slow and simple way to do it. You can use a variation of that method to do it much faster. Basically, you take the bits 32 at a time (from right to left), do the addition, output the resulting 32 bits, maintain the carry (if any), and then move left. You can do that with bytes, words, ints, or longs. Say you're doing it with bytes and your numbers are "010101010101010101010101" and "10110100110101001111". You would split them into 8-bit groups:
3 2 1
01010101 01010101 01010101
10110100 11010100 11111100
Grab the two bytes from group 1, convert them to int, add them, and output the first 8 bits of the result. If there is a ninth bit to the result (there can't be more than 9 bits), then it's a carry into the next column of numbers.
Continue that until you've finished the last column of numbers. As I said, you can do that with any integral type (byte, short, int, long) to speed up the basic algorithm I laid out for individual bits.
I have a char holding different characters, and I would like to print the binary value of these into two 4 bytes sections. I am adding a 1 at the beginning so that they would be 4 each.
System.out.println(1 + Integer.toString(mychar[i],2));
I am using a for loop to go through the different characters and create a table. By doing this I can get the binary value plus the one. But i don't know how to separate it into two 4 bytes.
Lets assume that mychar[i] holds the String bryan. The output should be the following.
b 1110 0010
r 1111 0010
y 1111 1001
a 1110 0001
n 1110 1110
My personal favorite for zero-padding a small number (that is, a byte, a short etc) when converted to binary is:
String binaryRep = Integer.toBinaryString( 0x100 | mychar[i] & 0xff ).substring(1);
The & makes sure that no more than 8 bits are taken from mychar[i]
The 0x100 | part sets the 9th bit. This means all the zeros in the rightmost 8 bits will be represented in the result, which will be exactly 9 characters long.
Then taking the substring from 1 makes sure we take just the 8.
Of course, the above assumes a character that fits into 8 bits. If you try a Chinese or Arabic character it will basically just give you its rightmost 8 bits.
Whatever method you use for producing 8 zero-padded bits, you'll need to add the space in the middle. For my method above, we can make this modification:
public static String eightBitCharToBinary( char c ) {
String charAsNineBits = Integer.toBinaryString( 0x100 | c & 0xff );
return charAsNineBits.substring(1,5) + " " + charAsNineBits.substring(5,9);
}
Which does the same as above, but instead of just taking one substring, takes two substrings and puts a space in the middle.
I've used this answer to come to a solution:
private static String toBinaryRepresentation(String name) {
// 11 is size of "0000 0000\r\n
StringBuilder sb = new StringBuilder(name.length() * 11);
for (int i = 0; i < name.length(); i++) {
String binRep = toBinaryRepresentation(name.charAt(i));
sb.append(String.format("%s%n", binRep));
}
return sb.toString();
}
private static String toBinaryRepresentation(char c) {
if (c > 0xFF) {
throw new IllegalArgumentException("Character value too high to print");
}
int highNibble = (c >> 4) & 0xF;
String highBinaryDigits = String.format("%4s", Integer.toBinaryString(highNibble)).replace(' ', '0');
int lowNibble = c & 0xF;
String lowBinaryDigits = String.format("%4s", Integer.toBinaryString(lowNibble)).replace(' ', '0');
return String.format("%s %s", highBinaryDigits, lowBinaryDigits);
}
Which you can use by calling the function like this:
String name = "brian";
System.out.print(toBinaryRepresentation(name));
This prints:
0110 0010
0111 0010
0110 1001
0110 0001
0110 1110
So this first separates the high and low nibble and then prints the value using precisely 4 bits, even if they are zero.
public static void main(String []args){
String [] mychar = {"bryan"};
int len = mychar.length;
// iterate over each mychar element
for(int i =0; i< len ; i++){
// get the first string from array
String s = mychar[i];
int length = s.length();
//iterate over the string
for(int j =0; j< length ; j++){
char ch = s.charAt(j);
String str = Integer.toBinaryString(ch);
// print each char
System.out.print(ch+" : ");
System.out.println(str.substring(0,4)+" "+str.substring(3) );
}
}
}
char c = 'b';
String binaryString =Integer.toBinaryString(c);
System.out.println("1" + binaryString.substring(0, 3) + " " + binaryString.substring(3));
I have came across a question but I'm unable to optimize my code. Please tell me how can I optimize my code.
Scanner in = new Scanner(System.in);
int max=0;
int a = in.nextInt();
for(int i=1;i<a;i++){
for(int j=i+1;j<=a;j++)
{
int d = i^j;
if(d>max)
max=d;
}
}
System.out.println(max);
The explanation for the above code is:
The Xor of 1 and 2 is 3.
The Xor of 1 and 3 is 2.
The Xor of 2 and 3 is 1.
So, the maximum is 3.
Scanner in = new Scanner(System.in);
int a = in.nextInt();
System.out.println("Max = " + Double.toString(Math.pow(2, 1+Math.floor(Math.log(a)/Math.log(2)))-1.0));
Oops.. Doesn't work when a=0, but you should be able to adjust for that.
Explanation
For each possible input a, there is a number between 1 and a that equals not a (considering only as many binary digits as are in a itself). So, the max will always equal (2^n)-1, where n is the number of binary digits in a.
Okay, so the maximum you're looking for is all ones in a binary string of length of the binary string that represents your input value.
Your input value is 3, in binary it's '11', xor table:
0 xor 0 = 0
1 xor 0 = 1
0 xor 1 = 1
1 xor 1 = 0
so what you want is to xor the input value with the opposite value. Here the opposite value is the value with all bytes flipped.
In your example the length of the binary string is 2, so you need to get 2 ones. To achieve that you xor '10' and '01' or '01' and '10' and that's how you get 3.
But you can simply take the opposite of '11' which is '00' and xor those two and get 3 as well (as in the algorithm I described).
I have no idea how to flip a bit string of given length because the '~' operator will flip all 32 bits of an int, but alternatively you can implement it this way:
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
sc.close();
for(int i = 1; i < a; ++i) {
a |= i;
}
System.out.println(a);
}
}
Now your running time is linear and not quadratic, however you can also achieve the same result by doing:
1 << (int)(Math.log(a)/Math.log(2)) - 1;
I have a number , let say 4 which is in binary represented as 100 , what i will like to achieve is to complement the number i.e. replace 1 by 0 and 0 by 1 . I can achieve it like this
public class Foo {
public static void main(String[] args) {
String binaryString = Integer.toBinaryString(4);
StringBuilder out = new StringBuilder();
char[] chars = binaryString.toCharArray();
char x;
for (char ch : chars) {
if (ch == '1') {
x = '0';
} else {
x = '1';
}
out.append(x);
}
System.out.println(Integer.parseInt(out.toString(), 2));
}
}
What is the most efficient way to achieve the same result in terms of time complexity? Please note that input can be very big numbers and we need to take care of Integer overflow.
Updated
negating a number like ~n will give wrong result , for e.g.
System.out.println(~4);
outputs -5 , expected 3
What is the most efficient way to achieve the same result in terms of time complexity?
Given that the size of int is fixed at 32, the time complexity is O(1). Your program is pretty inefficient, though, because it creates a coupe of strings, does string parsing, and so on.
You can do this faster if you skip the conversion to binary altogether, and simply invert the number, like this:
int val = 4;
int msb = int msb = 32 - Integer.numberOfLeadingZeros(val);
int inverse = ~val & ((1 << msb)-1);
System.out.println(inverse);
The ~ operator is a unary operator that produces a binary complement of the value. The loop computes the position of the most significant bit (MSB). ((1 << msb)-1) is a mask that removes all bits higher than the MSB.
Demo.
You can try using bitwise negation:
private int flipBits(int n) {
return ~n;
}
Why not do something like this:
public static void main(String[] args) {
String binaryString = Integer.toBinaryString(4);
binaryString = binaryString.replaceAll("1", "-");
binaryString = binaryString.replaceAll("0", "1");
binaryString = binaryString.replaceAll("-", "0");
Only 3 lines of code to convert...
BigInteger allows you to use a number of arbitrary length. The way to find the negation is to find the max value possible given the input length and substract the input value from it
//you might want to validate that the string really is a binary number string
BigInteger myNum = new BigInteger(inputStr, 2);
BigInteger max = new BigInteger("2");
max = max.pow(inputStr.length()).subtract(new BigInteger("1"));
BigInteger ans = max.substract(myNum);
Say that I have
String input = "Programming", result="\0";
int temp;
for (int i=0;i<input.length();++i) {
temp = input.charAt(i);
result += temp;
}
result would be 8011411110311497109109105110103. I know that
P = 80
r = 114
o = 111
g = 103
r = 114
a = 97
m = 109
m = 109
i = 105
n = 110
g = 103
Out of curiosity, is it possible, in easy way, to reverse the process?
what you would have to do is assume that Each number lies between either 'A' to 'Z', (65 to 90) or 'a' to 'z' (97 to 122)
get the first 2 digits via a call to substring()
check if those lie within the above bounds by converting to a numeric type
if they do then continue with the loop
else get the third digit and check that
it would be much simpler if you could have it be padded to three digits so you would know that every three digits formed an ASCII letter
code that works only if it is letters:
public static void main(String[] args) {
String toConvert= "8011411110311497109109105110103";
String result="";
while(toConvert.length()>0){
String digits=toConvert.substring(0, 2);
int num=Integer.valueOf(digits);
if(('A'<=num&&num<='Z')||('a'<=num&&num<='z')){
toConvert=toConvert.substring(2);
}
else{
digits=toConvert.substring(0, 3);
num=Integer.valueOf(digits);
toConvert=toConvert.substring(3);
}
String letter = String.valueOf((char) num);
result+=letter;
}
System.out.println(result);
}
note if you change the test to num>25 , then it will correctly work for all ASCII values from 26 up: for values 26 to 99, it will interpret them as having 2 digits correctly, for values from 100 to 255 it will only look at the first 2 digits, so they will be seen as 10-25, and will be interpreted as 3 digits long