I have a string containing a hexadecimal value. Now I need the content of this string containing the hexadecimal as a byte variable. How should I do this without changing the hexadecimal value?
            Asked
            
        
        
            Active
            
        
            Viewed 2,453 times
        
    3
            
            
        - 
                    http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c – Dialecticus Feb 13 '11 at 18:02
- 
                    Not a duplicate (wrt C#) as far as I can tell. There are many variations, but this is specific ("xx" -> byte) and warrants a simpler answer than a number of the more complex scenarios. – Feb 13 '11 at 19:14
3 Answers
6
            An alternative to the options posted so far:
byte b = Convert.ToByte(text, 16);
Note that this will return 0 if text is null; that may or may not be the result you want.
 
    
    
        Jon Skeet
        
- 1,421,763
- 867
- 9,128
- 9,194
- 
                    1Damn, i even looked at the `Convert.ToByte` method but totally didn't spot that overload which takes the base as parameter... – H.B. Feb 13 '11 at 18:06
2
            
            
        String strHex = "ABCDEF";
Int32 nHex = Int32.Parse(strHex, NumberStyles.HexNumber);
Byte[] bHex = BitConverter.GetBytes(nHex);
I think that's what you're looking for. If not, post an update with a more explicit definition of what you're looking for.
 
    
    
        Brad Christie
        
- 100,477
- 16
- 156
- 200
1
            
            
        If it is just a single byte in the string, you can do this:
        string s = "FF";
        byte b;
        if (byte.TryParse(s, NumberStyles.HexNumber, null, out b))
        {
            MessageBox.Show(b.ToString());  //255
        }
 
    
    
        John Koerner
        
- 37,428
- 8
- 84
- 134
