How to convert string to hex in C#
By FoxLearn 2/3/2025 9:59:19 AM 660
In C#, you can convert a string to its hexadecimal representation by encoding the string into bytes and then converting each byte to its hexadecimal form.
Using Encoding.UTF8.GetBytes(input)
converts the input string to a byte array.
For example, c# string to hex
string StringToHex(string input) { // Convert the string to bytes using UTF-8 encoding byte[] bytes = Encoding.UTF8.GetBytes(input); // Build the hexadecimal representation StringBuilder sb = new StringBuilder(bytes.Length * 2); // c# hex foreach (byte b in bytes) sb.AppendFormat("{0:X2}", b); // Uppercase hex return sb.ToString(); }
Use a StringBuilder
to efficiently build the hex string, then use b.ToString("X2")
formats each byte as a 2-digit uppercase hexadecimal string. Use "x2"
for lowercase hex.
C# string format hex
In C#, you can format a number as a hexadecimal string using the ToString()
method with a format specifier.
int number = 255; string hex = number.ToString("X"); // Converts to uppercase hex, "FF" string hexLower = number.ToString("x"); // Converts to lowercase hex, "ff" Console.WriteLine(hex); // Output: FF Console.WriteLine(hexLower); // Output: ff
If you want to format a string with a specific width or padding, you can do that too:
int number = 255; string paddedHex = number.ToString("X4"); // Ensures 4 hex digits, "00FF" Console.WriteLine(paddedHex); // Output: 00FF
You can also format other types like long
, byte
, etc., in a similar way.
C# parse hex string
To parse a hexadecimal string into a number in C#, you can use Convert.ToInt32()
or int.Parse()
with the "X"
or "x"
format specifier.
For example, Using Convert.ToInt32()
:
string hexString = "FF"; // Hexadecimal string int number = Convert.ToInt32(hexString, 16); // Base 16 for hex Console.WriteLine(number); // Output: 255
For example, Using int.Parse()
:
string hexString = "FF"; // Hexadecimal string int number = int.Parse(hexString, System.Globalization.NumberStyles.HexNumber); // Parse with hex number style Console.WriteLine(number); // Output: 255
Both methods will convert the hex string "FF"
into the integer 255
. You can replace "FF"
with any valid hexadecimal string.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#