String to binary converter

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
1
down vote

favorite












I did research about binary counting, and wanted to make an application in Java that converts a string to binary code:



 /**
* This class converts strings by looping through the characters, gets the
* decimal code for each, then divides the number by 2 untill the quotient is 0
*
* @author Mr Pro Pop
*
*/
public class Binary

/**
* This function takes a string as a parameter and converts it to binary code
*
* @param string The string to be converted to binary code
* @return The binary code of the input string
*/

public String getBinaryCode(String string)

if (string.length() == 0)
return null;

char characters = string.toCharArray();
StringBuilder result = new StringBuilder();
int number = 0;

for (int i = 0; i < characters.length; i++)
number = getDecimal(characters[i]);
for (int j = 0; j < 8; j++)
if (number % 2 == 0)
result.insert(i, 0);
else
result.insert(i, 1);

number = (int) (number / 2);

result.append(" ");

return result.toString();


/**
* This function gets the decimal number of a character
*
* @param character The character that we want the decimal value of
* @return The decimal of the character from the ascii table
*/
public int getDecimal(char character)
for (int i = 0; i <= 255; i++)
if (character == (char) i)
return i;


return -1;


public static void main(String args)
String string = "a";
Binary b = new Binary();
System.out.println("Binary code for" + string + " is " + b.getBinaryCode(string));





Output:




Binary code for a is 01100001




Here it works well, however, spacing doesn't work. I do acknowledge that I could simply code this in a different easier method by Integer.toBinaryString(character[i]) but tried doing it my way to learn and especially with this method.



Any improvements I could do or anything to pay attention for?










share|improve this question



























    up vote
    1
    down vote

    favorite












    I did research about binary counting, and wanted to make an application in Java that converts a string to binary code:



     /**
    * This class converts strings by looping through the characters, gets the
    * decimal code for each, then divides the number by 2 untill the quotient is 0
    *
    * @author Mr Pro Pop
    *
    */
    public class Binary

    /**
    * This function takes a string as a parameter and converts it to binary code
    *
    * @param string The string to be converted to binary code
    * @return The binary code of the input string
    */

    public String getBinaryCode(String string)

    if (string.length() == 0)
    return null;

    char characters = string.toCharArray();
    StringBuilder result = new StringBuilder();
    int number = 0;

    for (int i = 0; i < characters.length; i++)
    number = getDecimal(characters[i]);
    for (int j = 0; j < 8; j++)
    if (number % 2 == 0)
    result.insert(i, 0);
    else
    result.insert(i, 1);

    number = (int) (number / 2);

    result.append(" ");

    return result.toString();


    /**
    * This function gets the decimal number of a character
    *
    * @param character The character that we want the decimal value of
    * @return The decimal of the character from the ascii table
    */
    public int getDecimal(char character)
    for (int i = 0; i <= 255; i++)
    if (character == (char) i)
    return i;


    return -1;


    public static void main(String args)
    String string = "a";
    Binary b = new Binary();
    System.out.println("Binary code for" + string + " is " + b.getBinaryCode(string));





    Output:




    Binary code for a is 01100001




    Here it works well, however, spacing doesn't work. I do acknowledge that I could simply code this in a different easier method by Integer.toBinaryString(character[i]) but tried doing it my way to learn and especially with this method.



    Any improvements I could do or anything to pay attention for?










    share|improve this question

























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I did research about binary counting, and wanted to make an application in Java that converts a string to binary code:



       /**
      * This class converts strings by looping through the characters, gets the
      * decimal code for each, then divides the number by 2 untill the quotient is 0
      *
      * @author Mr Pro Pop
      *
      */
      public class Binary

      /**
      * This function takes a string as a parameter and converts it to binary code
      *
      * @param string The string to be converted to binary code
      * @return The binary code of the input string
      */

      public String getBinaryCode(String string)

      if (string.length() == 0)
      return null;

      char characters = string.toCharArray();
      StringBuilder result = new StringBuilder();
      int number = 0;

      for (int i = 0; i < characters.length; i++)
      number = getDecimal(characters[i]);
      for (int j = 0; j < 8; j++)
      if (number % 2 == 0)
      result.insert(i, 0);
      else
      result.insert(i, 1);

      number = (int) (number / 2);

      result.append(" ");

      return result.toString();


      /**
      * This function gets the decimal number of a character
      *
      * @param character The character that we want the decimal value of
      * @return The decimal of the character from the ascii table
      */
      public int getDecimal(char character)
      for (int i = 0; i <= 255; i++)
      if (character == (char) i)
      return i;


      return -1;


      public static void main(String args)
      String string = "a";
      Binary b = new Binary();
      System.out.println("Binary code for" + string + " is " + b.getBinaryCode(string));





      Output:




      Binary code for a is 01100001




      Here it works well, however, spacing doesn't work. I do acknowledge that I could simply code this in a different easier method by Integer.toBinaryString(character[i]) but tried doing it my way to learn and especially with this method.



      Any improvements I could do or anything to pay attention for?










      share|improve this question















      I did research about binary counting, and wanted to make an application in Java that converts a string to binary code:



       /**
      * This class converts strings by looping through the characters, gets the
      * decimal code for each, then divides the number by 2 untill the quotient is 0
      *
      * @author Mr Pro Pop
      *
      */
      public class Binary

      /**
      * This function takes a string as a parameter and converts it to binary code
      *
      * @param string The string to be converted to binary code
      * @return The binary code of the input string
      */

      public String getBinaryCode(String string)

      if (string.length() == 0)
      return null;

      char characters = string.toCharArray();
      StringBuilder result = new StringBuilder();
      int number = 0;

      for (int i = 0; i < characters.length; i++)
      number = getDecimal(characters[i]);
      for (int j = 0; j < 8; j++)
      if (number % 2 == 0)
      result.insert(i, 0);
      else
      result.insert(i, 1);

      number = (int) (number / 2);

      result.append(" ");

      return result.toString();


      /**
      * This function gets the decimal number of a character
      *
      * @param character The character that we want the decimal value of
      * @return The decimal of the character from the ascii table
      */
      public int getDecimal(char character)
      for (int i = 0; i <= 255; i++)
      if (character == (char) i)
      return i;


      return -1;


      public static void main(String args)
      String string = "a";
      Binary b = new Binary();
      System.out.println("Binary code for" + string + " is " + b.getBinaryCode(string));





      Output:




      Binary code for a is 01100001




      Here it works well, however, spacing doesn't work. I do acknowledge that I could simply code this in a different easier method by Integer.toBinaryString(character[i]) but tried doing it my way to learn and especially with this method.



      Any improvements I could do or anything to pay attention for?







      java reinventing-the-wheel number-systems






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 10 mins ago









      200_success

      124k14144401




      124k14144401










      asked 2 hours ago









      Mr Pro Pop

      1204




      1204




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          I would change



          public int getDecimal(char character)

          for (int i = 0; i <= 255; i++)

          if (character == (char) i)

          return i;


          return -1;



          To just



          public int getDecimal(char character)

          if(character<0


          , As char is a number, too.



          Also try using >> operator to get nth binary digit, which means division by 2.



          number = (int) (number / 2);


          To



          number = number >>1;


          I don't know if it would be faster in java, but it works faster in old computer's assembly program(Division was expensive than just shifting)



          If you use assembly you can access carry flags and optimize it.



          For more information about it, refer here.



          Provided that al holds the target number and bx holds the target string address, and cx holds 8,




          L1: ; This is the loop
          mov dl, '0' ; Ascii character zero
          shl al, 1 ; Upper bit now in carry flag
          adc dl, 0 ; Adds carry flag - 0 or 1
          mov [bx], dl ; Save digit to current position
          inc bx ; Next position
          loop L1 ; Counts down cx
          mov [bx], 0 ; Zero terminate (might need to use register)






          share|improve this answer










          New contributor




          KYHSGeekCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.

















          • Oh thanks!!! Changed the getDecimal method. One thing I didn't quite get is the >> operator, what do you mean? And also one more question please, why is my append(" ") putting space after the result? So say I pass "sup" it would give the binary code of each character not separated and at the end put 3 spaces.
            – Mr Pro Pop
            1 hour ago










          • @MrProPop Maybe because of the insert method?
            – KYHSGeekCode
            1 hour ago










          • Aha, thanks for the tip. Btw, yes your right, the problem is because of insert, but if I don't use insert, then I would get the binary code the other way round, like flipped. Do I run a for loop to order them back? Just thought of it would consume more resources considering a large string looping through each character.
            – Mr Pro Pop
            1 hour ago







          • 1




            @MrProPop Maybe you can do that. Or if you use assembly language you can access carry flag which is set when it is shifted in certain conditions like the ooerand is even or its highst bit is 1, etc. Then you can naturally find bits from its highest bits.
            – KYHSGeekCode
            1 hour ago











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f204212%2fstring-to-binary-converter%23new-answer', 'question_page');

          );

          Post as a guest






























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          3
          down vote



          accepted










          I would change



          public int getDecimal(char character)

          for (int i = 0; i <= 255; i++)

          if (character == (char) i)

          return i;


          return -1;



          To just



          public int getDecimal(char character)

          if(character<0


          , As char is a number, too.



          Also try using >> operator to get nth binary digit, which means division by 2.



          number = (int) (number / 2);


          To



          number = number >>1;


          I don't know if it would be faster in java, but it works faster in old computer's assembly program(Division was expensive than just shifting)



          If you use assembly you can access carry flags and optimize it.



          For more information about it, refer here.



          Provided that al holds the target number and bx holds the target string address, and cx holds 8,




          L1: ; This is the loop
          mov dl, '0' ; Ascii character zero
          shl al, 1 ; Upper bit now in carry flag
          adc dl, 0 ; Adds carry flag - 0 or 1
          mov [bx], dl ; Save digit to current position
          inc bx ; Next position
          loop L1 ; Counts down cx
          mov [bx], 0 ; Zero terminate (might need to use register)






          share|improve this answer










          New contributor




          KYHSGeekCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.

















          • Oh thanks!!! Changed the getDecimal method. One thing I didn't quite get is the >> operator, what do you mean? And also one more question please, why is my append(" ") putting space after the result? So say I pass "sup" it would give the binary code of each character not separated and at the end put 3 spaces.
            – Mr Pro Pop
            1 hour ago










          • @MrProPop Maybe because of the insert method?
            – KYHSGeekCode
            1 hour ago










          • Aha, thanks for the tip. Btw, yes your right, the problem is because of insert, but if I don't use insert, then I would get the binary code the other way round, like flipped. Do I run a for loop to order them back? Just thought of it would consume more resources considering a large string looping through each character.
            – Mr Pro Pop
            1 hour ago







          • 1




            @MrProPop Maybe you can do that. Or if you use assembly language you can access carry flag which is set when it is shifted in certain conditions like the ooerand is even or its highst bit is 1, etc. Then you can naturally find bits from its highest bits.
            – KYHSGeekCode
            1 hour ago















          up vote
          3
          down vote



          accepted










          I would change



          public int getDecimal(char character)

          for (int i = 0; i <= 255; i++)

          if (character == (char) i)

          return i;


          return -1;



          To just



          public int getDecimal(char character)

          if(character<0


          , As char is a number, too.



          Also try using >> operator to get nth binary digit, which means division by 2.



          number = (int) (number / 2);


          To



          number = number >>1;


          I don't know if it would be faster in java, but it works faster in old computer's assembly program(Division was expensive than just shifting)



          If you use assembly you can access carry flags and optimize it.



          For more information about it, refer here.



          Provided that al holds the target number and bx holds the target string address, and cx holds 8,




          L1: ; This is the loop
          mov dl, '0' ; Ascii character zero
          shl al, 1 ; Upper bit now in carry flag
          adc dl, 0 ; Adds carry flag - 0 or 1
          mov [bx], dl ; Save digit to current position
          inc bx ; Next position
          loop L1 ; Counts down cx
          mov [bx], 0 ; Zero terminate (might need to use register)






          share|improve this answer










          New contributor




          KYHSGeekCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.

















          • Oh thanks!!! Changed the getDecimal method. One thing I didn't quite get is the >> operator, what do you mean? And also one more question please, why is my append(" ") putting space after the result? So say I pass "sup" it would give the binary code of each character not separated and at the end put 3 spaces.
            – Mr Pro Pop
            1 hour ago










          • @MrProPop Maybe because of the insert method?
            – KYHSGeekCode
            1 hour ago










          • Aha, thanks for the tip. Btw, yes your right, the problem is because of insert, but if I don't use insert, then I would get the binary code the other way round, like flipped. Do I run a for loop to order them back? Just thought of it would consume more resources considering a large string looping through each character.
            – Mr Pro Pop
            1 hour ago







          • 1




            @MrProPop Maybe you can do that. Or if you use assembly language you can access carry flag which is set when it is shifted in certain conditions like the ooerand is even or its highst bit is 1, etc. Then you can naturally find bits from its highest bits.
            – KYHSGeekCode
            1 hour ago













          up vote
          3
          down vote



          accepted







          up vote
          3
          down vote



          accepted






          I would change



          public int getDecimal(char character)

          for (int i = 0; i <= 255; i++)

          if (character == (char) i)

          return i;


          return -1;



          To just



          public int getDecimal(char character)

          if(character<0


          , As char is a number, too.



          Also try using >> operator to get nth binary digit, which means division by 2.



          number = (int) (number / 2);


          To



          number = number >>1;


          I don't know if it would be faster in java, but it works faster in old computer's assembly program(Division was expensive than just shifting)



          If you use assembly you can access carry flags and optimize it.



          For more information about it, refer here.



          Provided that al holds the target number and bx holds the target string address, and cx holds 8,




          L1: ; This is the loop
          mov dl, '0' ; Ascii character zero
          shl al, 1 ; Upper bit now in carry flag
          adc dl, 0 ; Adds carry flag - 0 or 1
          mov [bx], dl ; Save digit to current position
          inc bx ; Next position
          loop L1 ; Counts down cx
          mov [bx], 0 ; Zero terminate (might need to use register)






          share|improve this answer










          New contributor




          KYHSGeekCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          I would change



          public int getDecimal(char character)

          for (int i = 0; i <= 255; i++)

          if (character == (char) i)

          return i;


          return -1;



          To just



          public int getDecimal(char character)

          if(character<0


          , As char is a number, too.



          Also try using >> operator to get nth binary digit, which means division by 2.



          number = (int) (number / 2);


          To



          number = number >>1;


          I don't know if it would be faster in java, but it works faster in old computer's assembly program(Division was expensive than just shifting)



          If you use assembly you can access carry flags and optimize it.



          For more information about it, refer here.



          Provided that al holds the target number and bx holds the target string address, and cx holds 8,




          L1: ; This is the loop
          mov dl, '0' ; Ascii character zero
          shl al, 1 ; Upper bit now in carry flag
          adc dl, 0 ; Adds carry flag - 0 or 1
          mov [bx], dl ; Save digit to current position
          inc bx ; Next position
          loop L1 ; Counts down cx
          mov [bx], 0 ; Zero terminate (might need to use register)







          share|improve this answer










          New contributor




          KYHSGeekCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer








          edited 1 hour ago





















          New contributor




          KYHSGeekCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered 1 hour ago









          KYHSGeekCode

          1464




          1464




          New contributor




          KYHSGeekCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          KYHSGeekCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          KYHSGeekCode is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.











          • Oh thanks!!! Changed the getDecimal method. One thing I didn't quite get is the >> operator, what do you mean? And also one more question please, why is my append(" ") putting space after the result? So say I pass "sup" it would give the binary code of each character not separated and at the end put 3 spaces.
            – Mr Pro Pop
            1 hour ago










          • @MrProPop Maybe because of the insert method?
            – KYHSGeekCode
            1 hour ago










          • Aha, thanks for the tip. Btw, yes your right, the problem is because of insert, but if I don't use insert, then I would get the binary code the other way round, like flipped. Do I run a for loop to order them back? Just thought of it would consume more resources considering a large string looping through each character.
            – Mr Pro Pop
            1 hour ago







          • 1




            @MrProPop Maybe you can do that. Or if you use assembly language you can access carry flag which is set when it is shifted in certain conditions like the ooerand is even or its highst bit is 1, etc. Then you can naturally find bits from its highest bits.
            – KYHSGeekCode
            1 hour ago

















          • Oh thanks!!! Changed the getDecimal method. One thing I didn't quite get is the >> operator, what do you mean? And also one more question please, why is my append(" ") putting space after the result? So say I pass "sup" it would give the binary code of each character not separated and at the end put 3 spaces.
            – Mr Pro Pop
            1 hour ago










          • @MrProPop Maybe because of the insert method?
            – KYHSGeekCode
            1 hour ago










          • Aha, thanks for the tip. Btw, yes your right, the problem is because of insert, but if I don't use insert, then I would get the binary code the other way round, like flipped. Do I run a for loop to order them back? Just thought of it would consume more resources considering a large string looping through each character.
            – Mr Pro Pop
            1 hour ago







          • 1




            @MrProPop Maybe you can do that. Or if you use assembly language you can access carry flag which is set when it is shifted in certain conditions like the ooerand is even or its highst bit is 1, etc. Then you can naturally find bits from its highest bits.
            – KYHSGeekCode
            1 hour ago
















          Oh thanks!!! Changed the getDecimal method. One thing I didn't quite get is the >> operator, what do you mean? And also one more question please, why is my append(" ") putting space after the result? So say I pass "sup" it would give the binary code of each character not separated and at the end put 3 spaces.
          – Mr Pro Pop
          1 hour ago




          Oh thanks!!! Changed the getDecimal method. One thing I didn't quite get is the >> operator, what do you mean? And also one more question please, why is my append(" ") putting space after the result? So say I pass "sup" it would give the binary code of each character not separated and at the end put 3 spaces.
          – Mr Pro Pop
          1 hour ago












          @MrProPop Maybe because of the insert method?
          – KYHSGeekCode
          1 hour ago




          @MrProPop Maybe because of the insert method?
          – KYHSGeekCode
          1 hour ago












          Aha, thanks for the tip. Btw, yes your right, the problem is because of insert, but if I don't use insert, then I would get the binary code the other way round, like flipped. Do I run a for loop to order them back? Just thought of it would consume more resources considering a large string looping through each character.
          – Mr Pro Pop
          1 hour ago





          Aha, thanks for the tip. Btw, yes your right, the problem is because of insert, but if I don't use insert, then I would get the binary code the other way round, like flipped. Do I run a for loop to order them back? Just thought of it would consume more resources considering a large string looping through each character.
          – Mr Pro Pop
          1 hour ago





          1




          1




          @MrProPop Maybe you can do that. Or if you use assembly language you can access carry flag which is set when it is shifted in certain conditions like the ooerand is even or its highst bit is 1, etc. Then you can naturally find bits from its highest bits.
          – KYHSGeekCode
          1 hour ago





          @MrProPop Maybe you can do that. Or if you use assembly language you can access carry flag which is set when it is shifted in certain conditions like the ooerand is even or its highst bit is 1, etc. Then you can naturally find bits from its highest bits.
          – KYHSGeekCode
          1 hour ago


















           

          draft saved


          draft discarded















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f204212%2fstring-to-binary-converter%23new-answer', 'question_page');

          );

          Post as a guest













































































          Comments

          Popular posts from this blog

          Long meetings (6-7 hours a day): Being “babysat” by supervisor

          Is the Concept of Multiple Fantasy Races Scientifically Flawed? [closed]

          Confectionery