CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2012
    Posts
    4

    Question Convert ascii to hex

    Is there any code for converting ascii value to hex?
    For example converting 65(ascii of "A") to 41(hex)

  2. #2
    Join Date
    Feb 2004
    Location
    Seattle, USA
    Posts
    137

    Re: Convert ascii to hex

    Not sure I understand what you'd like to do. It sounds like you want to take the string "A" and convert it to the string "41". Is that correct?

    If so, then there are a couple of steps:
    1. convert the string to an integer
    2. convert the integer to a string in a different format

    For Example:
    Code:
    static string StringToHexValues(string input)
    {
        if (input == null) 
            throw new ArgumentNullException("input");
    
        StringBuilder sb = new StringBuilder();
        foreach (char c in input)
        {
            // Step 1: Convert to numeric type
            // NOTE: If you know 'input' is an ASCII string, then 
            // you can use a byte. However in C# you never can garuntee that...)
            int charVal = (int)c;
    
            // Step 2: Convert to string in hex format
            // NOTE: The "CultureInfo" isn't really necessary
            // in this case, but its always a good habit be explicit...
            string hexVal = charVal.ToString("X", CultureInfo.InvariantCulture);
    
            sb.Append(hexVal);
            sb.Append(" ");
        }
    
        return sb.ToString();
    }
    To see how this works:
    Code:
    Console.WriteLine(StringToHexValues("Hello World!"));
    Console.WriteLine(StringToHexValues("您好世界"));
    Produces
    Code:
    48 65 6C 6C 6F 20 57 6F 72 6C 64 21
    60A8 597D 4E16 754C
    Hope this helps
    Last edited by enfekted; August 5th, 2012 at 02:45 PM.

  3. #3
    Join Date
    Aug 2005
    Posts
    198

    Re: Convert ascii to hex

    ((int)'A').ToString("X")
    David Anton
    Convert between VB, C#, C++, & Java
    www.tangiblesoftwaresolutions.com
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter

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

Featured