Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a single hex character to its byte value in C#

Tags:

c#

.net

hex

This will convert 1 hex character to its integer value, but needs to construct a (sub) string.

Convert.ToInt32(serializedString.Substring(0,1), 16);

Does .NET have a built-in way to convert a single hex character to its byte (or int, doesn't matter) value that doesn't involve creating a new string?

like image 216
nos Avatar asked Jul 31 '09 21:07

nos


People also ask

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2];

Is 1 hex a byte?

Each Hexadecimal character represents 4 bits (0 - 15 decimal) which is called a nibble (a small byte - honest!). A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.

How many hex is 2 bytes?

That would be 16-number .

How do you convert hex to string?

In order to convert a hex string into a normal string, the hex string has to be converted into a byte array, which is indexed and converted into smaller hex strings of two digits. The smaller hex strings are then concatenated into a normal string. For some values, a two digit hex string will start with a zero.


2 Answers

int value = "0123456789ABCDEF".IndexOf(char.ToUpper(sourceString[index]));

Or even faster (subtraction vs. array search), but no checking for bad input:

int HexToInt(char hexChar)
{
    hexChar = char.ToUpper(hexChar);  // may not be necessary

    return (int)hexChar < (int)'A' ?
        ((int)hexChar - (int)'0') :
        10 + ((int)hexChar - (int)'A');
}
like image 156
Ben M Avatar answered Oct 06 '22 20:10

Ben M


Correct me if im wrong but can you simply use

Convert.ToByte(stringValue, 16);

as long as the stringValue represents a hex number? Isnt that the point of the base paramter?

Strings are immutable, I dont think there is a way to get the substring byte value of the char at index 0 without creating a new string

like image 39
almog.ori Avatar answered Oct 06 '22 21:10

almog.ori