Results 1 to 6 of 6

Thread: [RESOLVED] adding zero if byte is less than 10

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Sep 2013
    Posts
    107

    Resolved [RESOLVED] adding zero if byte is less than 10

    Hi

    I am converting a byte array to hex, problem is I lose the zero if the hex value is less than 10. I've tried googling the problem and cant seem to find a solution for my case.

    If you can spot something I've missed I'd appreciate it

    Code:
     
    1. Function BinaryToHex_Curve(ByRef binaryData As Byte()) As String
    2. Dim hexValue As String = ""
    3. Dim I32 As Int32
    4. For I32 = 4 To binaryData.Length - 1
    5. hexValue = hexValue + (String.Format("{0}", binaryData(I32).ToString("X")))
    6. Next
    7. Return hexValue
    8. End Function

  2. #2
    Addicted Member NinjaNic's Avatar
    Join Date
    Dec 2013
    Location
    Earth
    Posts
    230

    Re: adding zero if byte is less than 10

    Hex(int) returns a string based on the given integer. Try this in the for loop:

    Code:
    Dim hx As String = Hex(binaryData(I32))
    If hx.Length = 1 Then hexValue &= "0"
    hexValue &= hx
    Hope this helped!

    Nic

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Sep 2013
    Posts
    107

    Re: adding zero if byte is less than 10

    Cheers Nic, changed a couple of things but it did work.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,302

    Re: [RESOLVED] adding zero if byte is less than 10

    All you need do is change 'ToString("X")' to 'ToString("X2")'.

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,302

    Re: [RESOLVED] adding zero if byte is less than 10

    There's no good reason to have declared your 'binaryData' parameter ByRef in that code. You should do some reading and learn what ByRef is actually for. For a reference type, you should declare a parameter ByRef if and only if you want to assign a different object to the parameter inside the method and have that affect the original variable too. There is no other reason to declare a reference type parameter ByRef.

    As for your code, that can be simplified to this:
    vb.net Code:
    1. Return String.Skip(4).Concat(binaryData.Select(Function(b) b.ToString("X2"))

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Sep 2013
    Posts
    107

    Re: [RESOLVED] adding zero if byte is less than 10

    Thanks for all the reply's i'll take on board all that was said.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width