Hexadecimal to Binary Error Java -
i trying convert hexadecimal binary problem result ignoring zeroes should on left hand side crucial me.
my code:
public static void main(string[] args) { // todo auto-generated method stub scanner scan; int num; system.out.println("hexadecimal binary"); scan = new scanner(system.in); system.out.println("\nenter number :"); num = integer.parseint(scan.nextline(), 16); string binary = integer.tobinarystring(num); system.out.println("binary value : " + binary); }
output : when giving input 0000000000001a000d00
should output as
00000000000000000000000000000000000000000000000000011010000000000000110100000000
but instead 11010000000000000110100000000
leaving initial zeroes.
how should exact number. in advance.
you can try solution link (how 0-padded binary representation of integer in java?) provided @johnh, combined calculating length of binary representation of hex number. each hexadecimal digit requires 4 binary digits represent:
public static void main( string[] args ) { scanner scan; int num; system.out.println("hexadecimal binary"); scan = new scanner(system.in); system.out.println("\nenter number :"); string input = scan.nextline().trim(); num = integer.parseint(input, 16); int paddedlength = input.length() * 4; string binary = string.format("%"+ paddedlength +"s", integer.tobinarystring(num)).replace(' ', '0'); system.out.println("binary value : " + binary); }
it's not perfect, should trick.