usage StringBuilder in byte to hex conversion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stephaniee
    New Member
    • Dec 2009
    • 10

    usage StringBuilder in byte to hex conversion

    Hi,

    May I know why I ahve to use StringBuilder in Byte to Hex conversion? I saw a lot of samples conversion using this method.

    I have read stringbuilder article, but it doesnt provide any specific answer for my question.

    Your help will be appreciated.

    Thanks
  • stephaniee
    New Member
    • Dec 2009
    • 10

    #2
    this is the sample of ByteToHex conversion

    Code:
    private string ByteToHex(byte[] comByte)
            {
                
                StringBuilder builder = new StringBuilder(comByte.Length * 3);
                
                foreach (byte data in comByte)
              
                builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
                //return the converted value
                return builder.ToString().ToUpper();
            }
    Last edited by tlhintoq; Dec 18 '09, 06:49 AM. Reason: [CODE] ...Your code goes between code tags [/CODE]

    Comment

    • tlhintoq
      Recognized Expert Specialist
      • Mar 2008
      • 3532

      #3
      TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        When you tried rewriting the method without using the StringBuilder, did it still work? (Trial and error teaches a lot)

        You don't *have* to use a string builder, but in this case I would strongly recommend it.

        If you only used a string then you will each a lot of memory because a string is not truly resizable. If you re-assign the value of a string there is some fancy trickery on the part of Microsoft where a new memory space is assigned to the variable containing your new value. If you do this a lot, like you will in this loop, then you eat/waste a lot of space - at least until garbage collection takes place.

        Comment

        Working...