Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey people,

Curious problem I have, I want to convert a Hex value thats in a text box and get the actual representation to transport that. For Example say I enter A3D56712 in the text box, I want to get 0xA3, 0xD5, 0x67, 0x12, in HEX form.

Any Ideas?
Posted

Solution 1:

static string[] ToHexArray(uint value) {
    int len = sizeof(uint);
    string[] result = new string[len];
    for (int index = 0; index < len; ++index) {
        int shift = 8 * (len - index - 1);
        uint mask = (uint)byte.MaxValue << shift;
        uint masked = value & mask;   
        result[index] = ((byte)(masked >> shift)).ToString("X");
    } //loop
    return result;
}


Solution 2:

static string[] ToHexArray(uint value) {
    return System.Array.ConvertAll(
        System.BitConverter.GetBytes(value),
        new System.Converter<byte, string>(
            (src) => {
                return src.ToString("X");
        }));
}


First solution puts most significant figure at left (you can easily change it in code), second one — at right (Assembly language style; you cannot change it in algorithm but can reverse it later). You can add "0x" prefix to each string by using string.Format instead of ToString. You can use:
C#
string[] hexArray = ToHexArray(
    uint.Parse(
        MyTextBox.Text,
        System.Globalization.NumberStyles.HexNumber));


Both solutions are tested.

Enjoy!

—SA
 
Share this answer
 
v12
Comments
yesotaso 5-May-11 20:11pm    
My 5 + uint.Parse(MyTextBox.Text ,System.Globalization.NumberStyles.HexNumber).
I need some time to digest 2nd though :)
Sergey Alexandrovich Kryukov 5-May-11 20:18pm    
Thank you very much, especially for correcting my Parse.

As to the second algorithm, do yourself a favor, digest it (#1) System.BitConverter, #2)System.Array.ConvertAll) -- both are very good to know!

--SA
Why not just read extract two characters at a time and append "0x" to it?

Sorry, brain fart. I assume you want something more than this trivial response above.

See here[].
 
Share this answer
 
v2
Comments
yesotaso 5-May-11 10:43am    
The code fails if length of string is an odd number. If input is "1BD" which I think is a valid one substring fails :) Still a good one.
Andrew Rissing 5-May-11 15:06pm    
It'd be easy enough to pad the value with a zero if its odd (or something else equivalent), if the input is considered valid if it is an odd number of characters.
Sergey Alexandrovich Kryukov 5-May-11 19:50pm    
Not so elegant. My two solutions work in all cases and are more universal (can be used for decimal). My 4.
Please see.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900