I use in my C++/CLI project ToBase64String
to give a string like /MnwRx7kRZEQBxLZEkXndA==
I want to convert this string to Hexadecimal representation, How I can do that in C++/CLI or C#?
Asked
Active
Viewed 2.7k times
10

Aan
- 12,247
- 36
- 89
- 150
-
It seems quite stupid to convert to Base64 and then Hex a string. You could Hex directly the source. Unless you have other problems... – xanatos Oct 16 '11 at 13:04
-
unless all you have is the base64 string ... maybe he doesn't have the source. If so, then I agree. – bryanmac Oct 16 '11 at 13:11
-
Specifically, in Hans's answer [here](http://stackoverflow.com/questions/7774648/how-can-convert-this-c-sharp-code-to-c-cli/7774720#7774720), get rid of `ToBase64String` and use `BitConverter::ToString` instead. – Ben Voigt Oct 17 '11 at 17:33
3 Answers
32
FromBase64String will take the string
to byte
s
byte[] bytes = Convert.FromBase64String(string s);
Then, BitConverter.ToString()
will convert a byte array to a hex string ( byte[] to hex string )
string hex = BitConverter.ToString(bytes);

Max Voisard
- 1,685
- 1
- 8
- 18

bryanmac
- 38,941
- 11
- 91
- 99
0
public string Base64ToHex(string strInput)
{
try
{
var bytes = Convert.FromBase64String(strInput);
var hex = BitConverter.ToString(bytes);
return hex.Replace("-", "").ToLower();
}
catch (Exception)
{
return "-1";
}
}
On the contrary: https://stackoverflow.com/a/61224761/3988122

Meysam Ghorbani
- 55
- 4
0
Convert the string to a byte array and then do a byte to hex conversion
string stringToConvert = "/MnwRx7kRZEQBxLZEkXndA==";
byte[] convertedByte = Encoding.Unicode.GetBytes(stringToConvert);
string hex = BitConverter.ToString(convertedByte);
Console.WriteLine(hex);

Community
- 1
- 1

Ranhiru Jude Cooray
- 19,542
- 20
- 83
- 128
-
2I think the unicode.getbytes will treat that string as unicode chars when what you want is for the conversion to treat them as Base64. I think Convert.FromBase64String() does exactly that ... – bryanmac Oct 16 '11 at 13:10