How to convert string to hex in C#
By FoxLearn 11/26/2024 8:22:44 AM 116
To convert a string to its hexadecimal representation in C#, you can use the following method.
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:
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); 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.
- How to fix 'Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on'
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024