java - Concatenating zeros with a string -


i trying append zeros string make 32 bit number. output not show appended zeros. why so?

    system.out.print("\nenter linear address (32bit) :\t");     string linear_hex= sc.nextline();     string linear_bin= integer.tobinarystring(integer.parseint(linear_hex,16));      if(linear_bin.length() != 32)     {          for(int i= linear_bin.length(); i<=32; i++)             linear_bin= 0+linear_bin;     } 

output:

enter linear address (32bit) :  12345678 linear address = 10010001101000101011001111000 

i tried linear_bin= "0"+linear_bin; , "0".concat(linear_bin); output still same.

your code works fine me:

system.out.print("\nenter linear address (32bit) :\t");     scanner sc = new scanner(system.in);     string linear_hex= sc.nextline();     string linear_bin= integer.tobinarystring(integer.parseint(linear_hex,16));      if(linear_bin.length() != 32) {                  // should < 32 instead of <= 32, else end 0         // consider using stringbuilder instead of string concatenation here         for(int i= linear_bin.length(); < 32; i++)             linear_bin= 0+linear_bin;     }     system.out.println(linear_bin); 

input:

123456 

output:

00000000000100100011010001010110 

however, can achieve more using string.format() method. remove if block, , add print statement:

system.out.println(string.format("%32s", linear_bin).replace(' ', '0')); 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -