a5 hexadecimal to binary code example
Example 1: hexadecimal to binary in java
import java.util.Scanner;
public class HexadecimalToBinaryJava
{
public static void main(String[] args)
{
int decimalNumber, a = 1, b;
int[] binaryNumber = new int[100];
Scanner sc = new Scanner(System.in);
System.out.print("Please enter hexadecimal number: ");
String hexaDecimalNumber = sc.nextLine();
decimalNumber = toDecimal(hexaDecimalNumber);
while(decimalNumber != 0)
{
binaryNumber[a++] = decimalNumber % 2;
decimalNumber = decimalNumber / 2;
}
System.out.print("The equivalent binary number is: ");
for(b = a - 1; b > 0; b--)
{
System.out.print(binaryNumber[b]);
}
System.out.print("\n");
sc.close();
}
public static int toDecimal(String str)
{
String strDigits = "0123456789ABCDEF";
str = str.toUpperCase();
int val = 0;
for(int a = 0; a < str.length(); a++)
{
char c = str.charAt(a);
int d = strDigits.indexOf(c);
val = 16 * val + d;
}
return val;
}
}
Example 2: binary to hexadecimal in c
#include <stdio.h>
int main()
{
long int binaryval, hexadecimalval = 0, i = 1, remainder;
printf("Enter the binary number: ");
scanf("%ld", &binaryval);
while (binaryval != 0)
{
remainder = binaryval % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = binaryval / 10;
}
printf("Equivalent hexadecimal value: %lX", hexadecimalval);
return 0;
}