• Post Reply Bookmark Topic Watch Topic
  • New Topic

Explain this binary conversion code  RSS feed

 
Ryan Callen
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all, can anyone explain this code block to me? I do not need explanation on the obvious (for loop, printlns, etc), but rather the two lines within the for loop (the parseInt part). I'm not sure how this code is executing the conversion from binary to text.

String input = "011000010110000101100001";
String output = "";
for(int i = 0; i <= input.length() - 8; i+=8)
{
int k = Integer.parseInt(input.substring(i, i+8), 2);
output += (char) k;
}

System.out.println(output);
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The explanation is found in the docs for Integer.

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
 
Jayesh A Lalwani
Rancher
Posts: 2762
32
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can actually figure a lot of this out by either debugging through the code and inspecting variables, or adding log statements or heck just doing this on paper

SO, for i = 0

input.substring(i, i+8) will return "01100001"
Integer.parseInt("01100001",2 ) will return 97
(char)97 is 'a'
Output += ' a' will make output = "a"

For i=1
input.substring(i, i+8) will again return "01100001"
Integer.parseInt("01100001",2 ) will return 97
(char)97 is 'a'
Output += ' a' will make output = "aa"

For i=2
input.substring(i, i+8) will again return "01100001"
Integer.parseInt("01100001",2 ) will return 97
(char)97 is 'a'
Output += ' a' will make output = "aaa"

and that's how it works. You can do the exact same thing for any program by pretending to be the computer. Just go line by line by line and do exactly what you think the computer will do. If you don't know what the computer will do for the API.. look it up in the java doc.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!