Results 1 to 14 of 14

Thread: [RESOLVED] How to convert a HEX array to DEC ???

  1. #1

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    354

    Resolved [RESOLVED] How to convert a HEX array to DEC ???

    Hi all. I have a collection of raw hexadecimal bytes (2 digits each with a space between i.e. "5E A2 1C") which I want to convert and simultaneously, I want to separate each part with ',' but I don't know how.

    I came here with the idea below for second part:
    Code:
    Dim result as UInt16()
    TextBox1.Text = String.Empty
    For Each item As UInt16 In result
         TextBox1.Text = String.Format("{0}, ", item)
    Next
    But I'm really hopeful you guys will come with a better short and organize idea to do both at same time.
    Last edited by pourkascheff; Apr 25th, 2021 at 01:51 AM. Reason: Correction

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

    Re: How to convert a HEX array to DEC ???

    Think about the steps involved:

    1. Split the existing String on the spaces.
    2. Loop through the input to get the output.
    3. On each iteration, convert one hex string to a number.
    4. Convert each number to a decimal string.
    5. Combine the outputs into a single string.

    That's five completely separate steps that you can research independently and then ask questions about separately, if and when you encounter an actual issue. ALWAYS break the problem up into the simplest parts possible and address each part separately, then combine the partial solutions.

    So, where exactly is your actual issue?

  3. #3

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    354

    Re: How to convert a HEX array to DEC ???

    So, Here's the abstract scheme. Converting is now possible @ the same time. No more "," is needed due to fetching them in their desirable locations in every loop cycles.
    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim WORDS As String() = TextBox1.Text.Split(New Char() {" "c})
            Dim WORD As String
            For Each WORD In WORDS
    
                ListBox1.Items.Add(Convert.ToInt16(WORD))     'Converting each part occurs here
    
            Next
    ✔ It builds completely with no errors.
    ✖ But led to debug due to not recognizing A, B, C, D, E and F as match as variable type at runtime. ("Format exception was unhandled" Input string was not in a correct format.)
    ✖ Not even work fine with number inputs (All combinations of 0~999 acts like they're decimal numbers. It returns back them back with no changes).

    Today's Lesson not to forget: Using others codes ≅ Increasing troubles.

    *It should be noted that I am a pro microcontroller programmer. Only here cause of visual studio enthusiastic cool projects. I am at the "Lowest level". I deal with bits

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: How to convert a HEX array to DEC ???

    Right, Converet.ToInt16 will only convert strings that are already decimal numbers, and you know these are not. Therefore, it will convert "12", but not "1A", and it will convert "12" to 12, which is not what you want.

    However, there are overloads:

    https://docs.microsoft.com/en-us/dot...ngs-to-numbers
    My usual boring signature: Nothing

  5. #5

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    354

    Re: How to convert a HEX array to DEC ???

    Oh, so basically changing WORD and/or WORDS to byte, sbyte, uint16 or something that I don't know seem to be enough but in
    Code:
    Dim WORDS As String() = TextBox1.Text.Split(New Char() {" "c})
    errors will show up.
    What is that "c" after {" "c} even mean? And also new char in Split(New Char() ...) is a fix part of the format i guess according to the msdn.

  6. #6

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    354

    Re: How to convert a HEX array to DEC ???

    NO! My TextBox1.Text (or the WORD split from it) should be in 16th based. How can I tell the machine to consider that?

  7. #7

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    354

    Re: How to convert a HEX array to DEC ???

    Guess what? This code works for vice versa (From decimal to hexadecimal):
    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim WORDS As String() = TextBox1.Text.ToString.Split(New Char() {" "c})
            Dim WORD As Integer
            For Each WORD In WORDS
                ListBox1.Items.Add(Convert.ToString(WORD, 16))
            Next
    Didn't expect that that way is harder

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: How to convert a HEX array to DEC ???

    The 'c' is saying that " " is a character rather than a string. Those are two different types. You are creating an array of Char, so it can only take items of type Char. Without the 'c', then anything inside quotes will be a string, regardless of whether or not it is just a single character long.

    Did you look at the link I provided? The various Convert.ToInteger variants normally convert strings to integers, but they assume that the string they are trying to convert is a base 10 representation of the integer. In your case, the string they are trying to convert is a base 16 representation of the integer, so you have to use a variation of Convert.ToInteger to tell the computer that, which is what the link shows.

    I haven't looked to see whether there is a similar overload of Convert.ToInt16. There probably is, but there isn't much point in converting to an Int16....ever. You'd only really use that in certain rare embedded systems, as far as I can tell.
    My usual boring signature: Nothing

  9. #9

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    354

    Re: How to convert a HEX array to DEC ???

    Quote Originally Posted by Shaggy Hiker View Post
    Did you look at the link I provided?
    Yes Shaggy. I also read CStr, CChr, CSng, CDbl, etc. narrow conversion article which was really weird cool thing. I will read your reply again to figure it out but can anyone contribute with a tested code while I'm looking up? I thought you computer science people do these examples as your homework at least in north america.

  10. #10
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: How to convert a HEX array to DEC ???

    That link had the actual line of code that you needed.

    In your second post, you have this:

    Convert.ToInt16(WORD)

    That converts a string into a base 10 number, which isn't what you want, because the string is NOT a base 10 number. The string is a base 16 number. The link shows a method that converts a string that is a base 16 number into an integer.

    Frankly, I think this stems from a confusion between strings and numbers, and I have no idea how to explain that in a way that will shift your perspective.
    My usual boring signature: Nothing

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

    Re: How to convert a HEX array to DEC ???

    You already know that Convert.ToInt16 converts a String to a Short. You also know that Convert.ToString can take a base of 16 to convert TO a hexadecimal String. I wonder whether you can similarly use a base to convert FROM a hexadecimal String? The Parse and TryParse methods I mentioned will also converty from hexadecimal, although they do so a different way. All this information is provided in the official documentation.

    By the way, you don't need any arguments when calling String.Split. The default behaviour for that method is to split on whitespace so it will split on spaces if you don't tell it to split on anything else.
    vb.net Code:
    1. Dim words = myString.Split()
    2. Dim upperBound = words.GetUpperBound(0)
    3. Dim numbers(upperBound) As Short
    4.  
    5. For i = 0 To upperBound
    6.     'Get word from first array, convert to number and set in second array.
    7. Next

  12. #12

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    354

    Re: How to convert a HEX array to DEC ???

    You people won't believe me what I just found. (Other function part of the code pre-wrote)

    - Changing X to G converts the formatting from hexadecimal to decimal.
    - Number after that means digits per number.
    Code:
    Dim result As String = String.Empty
            For Each item As Byte In values
                result += String.Format("{0:X2} ", item)
            Next
            Return result
    Did you people aware of this?


    ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


    I will not close this case cause another challenge showed up XD Consider numbers below.
    Code:
    01 04 00 08 D9 1A 0E
    Mentioned code (with "G" as format) returns this:
    Code:
    1 4 0 8 217 26 14
    Which is incorrect because this piece of hex frames are Modbus RTU responses (In order: SlaveAddress, CommandCode, HoldingRegister, Data....Data, CRC0, CRC1) are considered of 2 bytes each per a data.
    Code:
    1 4 0 2265 6670‬
    To achieve a reliable answer, What the project requires could be divided in smaller parts as Jmcilhinney said:
    - Removing/Ignoring first 3 Bytes.
    - Merging each 2 Bytes after till end.

    1) Multiplying First byte (Most significant) in hundred (Hexadecimal) then adding Second byte (Less significant)
    2) Or in powering/exponentiation of that wrong decimal numbers to correct it
    Would be possible ways for second checkpoint right?

    Please help...

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: How to convert a HEX array to DEC ???

    I don't know what you're talking about with that first part. "Don't believe you"? Having looked back over the rest of the thread, the code you posted there doesn't appear to resemble anything else, so I'm not sure what there is to believe or disbelieve. What is values? Depending on the answer to that question, I think we've either been not understanding what you were asking. Was it in some other thread?

    If values is the string of bytes, then you're almost right in your steps, but not quite.

    There are bit shift operators, which can be more efficient than multiplication. For example, you could do this:

    dim res As Integer = (highByte << 8) Or lowByte

    Now, you might make res an UInt16 if you want it to be just two bytes, but don't use an Int16, as the high bit of that isn't free. If you just want the bytes, then the UInt16 is reasonable, but if you want to turn that number into a string, then use an integer, because it will be somewhat more efficient.

    The alternative would be:

    Dim res As Integer = (highByte * 256) + lowByte

    or else, as you stated:

    Dim res As Integer (highByte * &H100) + lowByte

    Theoretically, the bit shifting/bit manipulation approach would be somewhat faster than the other two, but in practice I'm not sure that's true in .NET.
    My usual boring signature: Nothing

  14. #14
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,754

    Re: How to convert a HEX array to DEC ???

    Quote Originally Posted by pourkascheff View Post
    Hi all. I have a collection of raw hexadecimal bytes (2 digits each with a space between i.e. "5E A2 1C") which I want to convert and simultaneously, I want to separate each part with ',' but I don't know how.

    I came here with the idea below for second part:
    Code:
    Dim result as UInt16()
    TextBox1.Text = String.Empty
    For Each item As UInt16 In result
         TextBox1.Text = String.Format("{0}, ", item)
    Next
    But I'm really hopeful you guys will come with a better short and organize idea to do both at same time.
    Code:
            'Hi all. I have a collection of raw hexadecimal bytes (2 digits each with a space between i.e. "5E A2 1C") 
            '  which I want to convert and simultaneously, I want to separate each part with ',' but I don't know how.
    
            Dim TESTinp As String = "5E A2 1C FF"
    
            '   which I want to convert - YOU did not say to what
            Dim cnvrt As List(Of Byte)
            cnvrt = (From b As String In TESTinp.Split
                        Select Byte.Parse(b, Globalization.NumberStyles.HexNumber)).ToList
    
            '   and simultaneously, I want to separate each part with ','
            Dim sb As New System.Text.StringBuilder
            For Each b As Byte In cnvrt
                sb.Append(b.ToString("X2"))
                sb.Append(", ")
            Next
            sb.Length -= 2
            Debug.WriteLine(sb.ToString)
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

Tags for this Thread

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