在 Vb.Net 中将字符串转换为十六进制字符串,反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15199656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting String to String of Hex and vice-versa in Vb.Net
提问by HypeZ
I need to convert a String of totally random characters in something i can read back! My idea is:
我需要将一个完全随机字符的字符串转换成我可以读回来的东西!我的想法是:
Example String: hi
示例字符串:嗨
h (Ascii) -> 68 (hex)
i (Ascii) -> 69 (hex)
So converting hii must have 6869
所以转换hi我必须有6869
My value is now in Base64(i got it with a Convert.ToBase64String()), is this "ascii to hex" conversion correct? In base64 i have value like "4kIw0ueWC/+c=" but i need charactersonly, special characters can mess my system
我的值现在在Base64(我用一个Convert.ToBase64String()),这个“ascii 到十六进制”转换正确吗?在 base64 中,我有像“4kIw0ueWC/+c=”这样的值,但我只需要字符,特殊字符会弄乱我的系统
The vb.net Convert can only translate to base64 string :(
vb.net Convert 只能转换为 base64 字符串 :(
edit: This is my final solution:
i got the base64 string inside my encvariable and converted it first in ASCII then in corrispondent Hex using:
编辑:这是我的最终解决方案:我在我的enc变量中获取了 base64 字符串,并首先使用 ASCII 将其转换为相应的十六进制:
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(enc)
Dim hex As String = BitConverter.ToString(bytes).Replace("-", String.Empty)
After that i reversed this with:
之后我用以下方法扭转了这一点:
Dim b((input.Length \ 2) - 1) As Byte
For i As Int32 = 0 To b.GetUpperBound(0)
b(i) = Byte.Parse(input.Substring(i * 2, 2), Globalization.NumberStyles.HexNumber)
Next i
Dim enc As New System.Text.ASCIIEncoding()
result = enc.GetString(b)
After all this i got back my base64string and converted one last time with Convert.FromBase64String(result)
毕竟这一切我找回了我的 base64string 并最后一次转换了 Convert.FromBase64String(result)
Done! Thanks for the hint :)
完毕!谢谢你的提示:)
回答by MarcinJuraszek
First get Byte()from your base64string:
首先Byte()从你的base64字符串中获取:
Dim data = Convert.FromBase64String(inputString)
Then use BitConverter:
然后使用BitConverter:
String hex = BitConverter.ToString(data)

