How to convert string to hex in C#
By FoxLearn 11/26/2024 8:22:44 AM 59
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 get application folder path in C#
- How to copy data to clipboard in C#
- How to mark a method as obsolete or deprecated in C#
- How to Call the Base Constructor in C#
- Deep Copy of Object in C#
- How to Catch Multiple Exceptions in C#
- How to cast int to enum in C#
- What is the difference between String and string in C#?
Categories
Popular Posts
SB Admin Template
11/17/2024
RuangAdmin Template
11/17/2024
DASHMIN Admin Dashboard Template
11/17/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024