如何将十六进制字符串转换为数字并以简单的方式计算总和。
我想每隔一秒切一次字符串 - > BB6050C9 ---> BB | 60 | 50 | C9
String shex = "BB6050C9";
int sum;
使用shex.Substring(....)我可以剪切字符串但是如何将字符串转换为数字并以简单的方式求和?
0xBB = 187,0x60 = 97,0x50 = 80,0xC9 = 201,
sum=187+97+80+201;
答案 0 :(得分:1)
使用SoapHexBinary.Parse然后对Value
属性返回的字节求和。
var shb = SoapHexBinary.Parse("BB6050C9");
var sum = shb.Value.Sum(x => x);//returns 564
答案 1 :(得分:0)
写下以下代码: -
var output = 0;
string input = "BB6050C9";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
// Get the integral value of the character.
int value = Convert.ToInt32(letter);
// Convert the decimal value to a hexadecimal value in string form.
string hexOutput = String.Format("{0:X}", value);
Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
output += Convert.ToInt32(hexOutput);
}
Console.WriteLine(output);
Console.ReadKey();
答案 2 :(得分:0)
String str = "BB6050C9";
const int chunkSize = 2;
var sum = Enumerable.Range(0, str.Length / chunkSize)
.Select(x => str.Substring(x * chunkSize, chunkSize))
.Sum(x => int.Parse(x, System.Globalization.NumberStyles.HexNumber));
Console.WriteLine(sum);
答案 3 :(得分:0)
给定一个十六进制字节的字符串(即2个字符),则值为:
16 * "0123456789abcdef".IndexOf(hex.ToLower()[0]) + "0123456789abcdef".IndexOf(hex.ToLower()[1])
答案 4 :(得分:0)
您可以使用正则表达式拆分字符串,使用Convert.ToInt32
解析数字并总结如下所示的值:
int sum = Regex.Matches(shex, "..").Cast<Match>()
.Select(m => Convert.ToInt32(m.Value, 16))
.Sum();
答案 5 :(得分:0)
String hex = "BB6050C9";
int i = 0;
long sum = 0;
while (i + 2 <= hex.Length)
{
sum += Convert.ToInt64(hex.Substring(i, 2), 16);
i += 2;
}
Console.WriteLine(sum);