Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Hex String into number

Hex String into number

Scheduled Pinned Locked Moved C#
tutorialcsharphelpquestion
17 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S snorkie

    I felt bad about giving a bad answer, so I wrote a whole program to do this. Hope this helps... Sorry I was too lazy to comment the code.

    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace ReverseHex
    {
    class Program
    {
    static void Main(string[] args)
    {
    string hexValue = Console.ReadLine();

            int finalNumber = 0;
            int multiplyCount = 0;
            for (int x = hexValue.Length - 1; x >= 0; x--)
            {
                int tempAdd = multiplyCount \* 15;
    
                switch (hexValue\[x\])
                {
                    case '1':
                        finalNumber += tempAdd + 1;
                        break;
                    case '2':
                        finalNumber += tempAdd + 2;
                        break;
                    case '3':
                        finalNumber += tempAdd + 3;
                        break;
                    case '4':
                        finalNumber += tempAdd + 4;
                        break;
                    case '5':
                        finalNumber += tempAdd + 5;
                        break;
                    case '6':
                        finalNumber += tempAdd + 6;
                        break;
                    case '7':
                        finalNumber += tempAdd + 7;
                        break;
                    case '8':
                        finalNumber += tempAdd + 8;
                        break;
                    case '9':
                        finalNumber += tempAdd + 9;
                        break;
                    case 'A':
                    case 'a':
                        finalNumber += tempAdd + 10;
                        break;
                    case 'B':
                    case 'b':
                        finalNumber += tempAdd + 11;
                        break;
                    case 'C':
                    case 'c':
                        finalNumber += tempAdd + 12;
                        break;
                    case 'D':
                    case 'd':
                        finalNumber += tempAdd + 13;
                        break;
                    case 'E':
                    case 'e':
                        finalNumber += tempAdd + 14;
                        break;
                    case 'F':
                    case 'f':
                        finalNumber += tempAdd + 15;
                        br
    
    L Offline
    L Offline
    leppie
    wrote on last edited by
    #8

    snorkie wrote:

    I felt bad about giving a bad answer

    Dude, this is a coding horror! ;P Go improve it now!!! Surely you can spot the pattern :)

    xacc.ide - now with TabsToSpaces support
    IronScheme - 1.0 alpha 4a out now (29 May 2008)

    S S 2 Replies Last reply
    0
    • L leppie

      snorkie wrote:

      I felt bad about giving a bad answer

      Dude, this is a coding horror! ;P Go improve it now!!! Surely you can spot the pattern :)

      xacc.ide - now with TabsToSpaces support
      IronScheme - 1.0 alpha 4a out now (29 May 2008)

      S Offline
      S Offline
      snorkie
      wrote on last edited by
      #9

      Its already bad enough that I did his homework for him... I don't want to make it too nice! Hogan

      B 1 Reply Last reply
      0
      • S snorkie

        I felt bad about giving a bad answer, so I wrote a whole program to do this. Hope this helps... Sorry I was too lazy to comment the code.

        using System;
        using System.Collections.Generic;
        using System.Text;

        namespace ReverseHex
        {
        class Program
        {
        static void Main(string[] args)
        {
        string hexValue = Console.ReadLine();

                int finalNumber = 0;
                int multiplyCount = 0;
                for (int x = hexValue.Length - 1; x >= 0; x--)
                {
                    int tempAdd = multiplyCount \* 15;
        
                    switch (hexValue\[x\])
                    {
                        case '1':
                            finalNumber += tempAdd + 1;
                            break;
                        case '2':
                            finalNumber += tempAdd + 2;
                            break;
                        case '3':
                            finalNumber += tempAdd + 3;
                            break;
                        case '4':
                            finalNumber += tempAdd + 4;
                            break;
                        case '5':
                            finalNumber += tempAdd + 5;
                            break;
                        case '6':
                            finalNumber += tempAdd + 6;
                            break;
                        case '7':
                            finalNumber += tempAdd + 7;
                            break;
                        case '8':
                            finalNumber += tempAdd + 8;
                            break;
                        case '9':
                            finalNumber += tempAdd + 9;
                            break;
                        case 'A':
                        case 'a':
                            finalNumber += tempAdd + 10;
                            break;
                        case 'B':
                        case 'b':
                            finalNumber += tempAdd + 11;
                            break;
                        case 'C':
                        case 'c':
                            finalNumber += tempAdd + 12;
                            break;
                        case 'D':
                        case 'd':
                            finalNumber += tempAdd + 13;
                            break;
                        case 'E':
                        case 'e':
                            finalNumber += tempAdd + 14;
                            break;
                        case 'F':
                        case 'f':
                            finalNumber += tempAdd + 15;
                            br
        
        A Offline
        A Offline
        aman2006
        wrote on last edited by
        #10

        Snorkie Thanks for the solution but it is not giving me the correct number still. for Hex string 100000 value should be 16. 060100= 262 1C0000= 28 Any other suggestion please. I am running out of my module time. Please reply. Thanks Shailesh

        1 Reply Last reply
        0
        • S snorkie

          Its already bad enough that I did his homework for him... I don't want to make it too nice! Hogan

          B Offline
          B Offline
          Brady Kelly
          wrote on last edited by
          #11

          Whew!

          1 Reply Last reply
          0
          • A aman2006

            Hello I have one question regading the conversion of Hex String into Decimal number. Hex Number is in format “aaaaaa” This 24-bit field is the direction “A” counter stored LS-byte first. Example is, take this hex string "100000" which is decimal equivalent is 16 But i don't know how to convert this number into decimal number. If i give this number to C# function it is not giving me the exact 16 equivalent. Another exanples are 060100= 262 1C0000= 28 Can any body please help me how to convert these numbers into decimal equivalent using C# Thanks Shailesh

            L Offline
            L Offline
            Luc Pattyn
            wrote on last edited by
            #12

            Hi, this would be my approach in pseudo-code:

            int result=0;
            while(stringLength!=0) {
            int oneByte=0;
            int.TryParse(rightmost2characters, hexSpecifier, out=oneByte);
            result=(result<<8)+oneByye;
            drop2charsFromString;
            }

            :)

            Luc Pattyn [Forum Guidelines] [My Articles]


            Voting for dummies? No thanks. X|


            1 Reply Last reply
            0
            • A aman2006

              Hello I have one question regading the conversion of Hex String into Decimal number. Hex Number is in format “aaaaaa” This 24-bit field is the direction “A” counter stored LS-byte first. Example is, take this hex string "100000" which is decimal equivalent is 16 But i don't know how to convert this number into decimal number. If i give this number to C# function it is not giving me the exact 16 equivalent. Another exanples are 060100= 262 1C0000= 28 Can any body please help me how to convert these numbers into decimal equivalent using C# Thanks Shailesh

              C Offline
              C Offline
              carbon_golem
              wrote on last edited by
              #13

              I'd convert the hex digits into a byte array, figure out what your target Type is, pad/swap as necessary. 24 bit types are a curse on the land handed down from angry gods to punish us for the sins of BIT-BANGERS.... sorry.... X| class Program { static void Main(string[] args) { String s = "100000"; Byte[] temp = new Byte[4]; // int needs 4 bytes Array.Copy(GetBytes(s), 0, temp, 0, 3); // copy in the byte converted string Int32 value = BitConverter.ToInt32(temp, 0); // use BitConverter to change Console.WriteLine(value.ToString()); // format Console.ReadLine(); // wait for non-google searching OP to push something } public static byte[] GetBytes(string hexFormat) { int byteLength = hexFormat.Length / 2; byte[] bytes = new byte[byteLength]; for (int i = 0; i < byteLength; i++) { bytes[i] = AsciiAsHexToByte(new String(new Char[] { hexFormat[i * 2], hexFormat[i * 2 + 1] })); } return bytes; } public static byte AsciiAsHexToByte(string hex) { return byte.Parse(hex, NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo); } }
              As you can see, it's a pain to do the conversion. Scott P

              “It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.” -Edsger Dijkstra

              1 Reply Last reply
              0
              • L leppie

                snorkie wrote:

                I felt bad about giving a bad answer

                Dude, this is a coding horror! ;P Go improve it now!!! Surely you can spot the pattern :)

                xacc.ide - now with TabsToSpaces support
                IronScheme - 1.0 alpha 4a out now (29 May 2008)

                S Offline
                S Offline
                Spacix One
                wrote on last edited by
                #14

                Nothing wrong with a nice For-Case design pattern :) http://thedailywtf.com/Articles/The_FOR-CASE_paradigm.aspx[^]


                -Spacix All your skynet questions[^] belong to solved


                I dislike the black-and-white voting system on questions/answers. X|


                1 Reply Last reply
                0
                • A aman2006

                  Hello I have one question regading the conversion of Hex String into Decimal number. Hex Number is in format “aaaaaa” This 24-bit field is the direction “A” counter stored LS-byte first. Example is, take this hex string "100000" which is decimal equivalent is 16 But i don't know how to convert this number into decimal number. If i give this number to C# function it is not giving me the exact 16 equivalent. Another exanples are 060100= 262 1C0000= 28 Can any body please help me how to convert these numbers into decimal equivalent using C# Thanks Shailesh

                  S Offline
                  S Offline
                  Spacix One
                  wrote on last edited by
                  #15

                  I'll 1/2 do your homework for ya ;)

                  Imports System
                  Imports System.Globalization
                  Imports System.Text

                  Module Module1
                  Sub Main()
                  Dim sb As New StringBuilder("1C0000")
                  Dim str As String
                  Dim value As Integer
                  Dim bval As Byte
                  Dim j As Double

                      If (sb.Length Mod 2) = 1 Then
                          sb.Append("0")
                      End If
                      str = sb.ToString()
                      For i As Integer = 1 To str.Length Step 2
                          j = Math.Pow(16, Convert.ToDouble(i - 1))
                          bval = Byte.Parse(Mid(str, i, 2), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo)
                          value += Convert.ToInt32(Convert.ToDouble(bval) \* j)
                      Next
                      Console.WriteLine("The string {0} is equal to {1}", sb.ToString(), value)
                  End Sub
                  

                  End Module

                  :laugh: (doh! fixed logic typo)


                  -Spacix All your skynet questions[^] belong to solved


                  I dislike the black-and-white voting system on questions/answers. X|


                  modified on Friday, June 20, 2008 4:25 PM

                  G 1 Reply Last reply
                  0
                  • S Spacix One

                    I'll 1/2 do your homework for ya ;)

                    Imports System
                    Imports System.Globalization
                    Imports System.Text

                    Module Module1
                    Sub Main()
                    Dim sb As New StringBuilder("1C0000")
                    Dim str As String
                    Dim value As Integer
                    Dim bval As Byte
                    Dim j As Double

                        If (sb.Length Mod 2) = 1 Then
                            sb.Append("0")
                        End If
                        str = sb.ToString()
                        For i As Integer = 1 To str.Length Step 2
                            j = Math.Pow(16, Convert.ToDouble(i - 1))
                            bval = Byte.Parse(Mid(str, i, 2), NumberStyles.HexNumber, NumberFormatInfo.CurrentInfo)
                            value += Convert.ToInt32(Convert.ToDouble(bval) \* j)
                        Next
                        Console.WriteLine("The string {0} is equal to {1}", sb.ToString(), value)
                    End Sub
                    

                    End Module

                    :laugh: (doh! fixed logic typo)


                    -Spacix All your skynet questions[^] belong to solved


                    I dislike the black-and-white voting system on questions/answers. X|


                    modified on Friday, June 20, 2008 4:25 PM

                    G Offline
                    G Offline
                    Guffa
                    wrote on last edited by
                    #16

                    What's the other half? Converting it to C#? ;)

                    I dislike the black-and-white voting system on questions/answers.

                    I agree that it's less nuanced, but on the other hand I see a huge increase in the usage of the voting system. It doesn't matter how good a system is, if noone uses it. :)

                    Despite everything, the person most likely to be fooling you next is yourself.

                    S 1 Reply Last reply
                    0
                    • G Guffa

                      What's the other half? Converting it to C#? ;)

                      I dislike the black-and-white voting system on questions/answers.

                      I agree that it's less nuanced, but on the other hand I see a huge increase in the usage of the voting system. It doesn't matter how good a system is, if noone uses it. :)

                      Despite everything, the person most likely to be fooling you next is yourself.

                      S Offline
                      S Offline
                      Spacix One
                      wrote on last edited by
                      #17

                      Guffa wrote:

                      What's the other half? Converting it to C#?

                      You are correct sir! :D There are a few other "optimizations" to be done which I would assume would garner a better grade from the original...

                      Guffa wrote:

                      It doesn't matter how good a system is, if noone uses it.

                      aye, but I think the giant images is what made people start clicking it over the little "Rate this message: {thumb down vote 1} 1 2 3 4 5 {thumb up vote 5}"


                      -Spacix All your skynet questions[^] belong to solved


                      I dislike the black-and-white voting system on questions/answers. X|


                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups