简体   繁体   English

C#-将十六进制值的字符串转换为十六进制

[英]C# - Convert a string of hex values to hex

This might sound odd, but my issue is that I have a text string of hex values from a text file, like so: 这听起来可能很奇怪,但是我的问题是我有一个来自文本文件的十六进制值的文本字符串,如下所示:

"0x0f, 0x40, 0xff, ...."

I have stored them in an array split by the delimiters, but what I now need to do is have a byte array of what thay are in hex: 我将它们存储在一个由定界符分隔的数组中,但是我现在需要做的是用十六进制表示一个字节数组:

stringArray[0] = "0x0f";

byteArray[0] = 0x0f;

How do I do this (the user can load the text file, so I don't know what the values are), is there some sort of arithmetic I can use? 我该怎么做(用户可以加载文本文件,所以我不知道值是什么),我可以使用某种算术吗?

If your string is in the correct format you can create your array using this code (will throw exceptions if the input is badly formatted): 如果字符串格式正确,则可以使用以下代码创建数组(如果输入格式错误,则会引发异常):

var text = "0x0f, 0x40, 0xff";
var bytes = text
  .Split(new[] { ", " }, StringSplitOptions.None)
  .Select(s => (Byte) Int32.Parse(s.Substring(2), AllowHexSpecifier));

You just have to parse each string. 您只需要解析每个字符串。 Because each one is already only one value, you can do this: 因为每个值仅是一个值,所以您可以执行以下操作:

byte b;
if (byte.TryParse(s, NumberStyles.HexNumber, 
    CultureInfo.InvariantCulture.NumberFormat, out b)) 
{
    // b contains the value.
}

where s is the string you want to parse, and b is the resulting value. 其中s是要解析的字符串,b是结果值。

Non of Odd hex string is correct. 非奇数十六进制字符串是正确的。 Check source from you get this string . 从中检查源是否获得此字符串。 It is because of truncation of string due to limit no of characters. 这是由于限制字符数而导致的字符串截断。 If String is image is stored in database then retrieve it using program not using any tools 如果String是图像存储在数据库中,则使用程序而不使用任何工具来检索它

I was having same problem with .net and MSSQL and by using webservice and Java Client 我在使用.net和MSSQL以及通过使用webservice和Java Client时遇到相同的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM