并对十六进制字符串进行操作

时间:2016-12-16 10:20:36

标签: c# .net

我有两个长度为8位的十六进制字符串。如何对这两个进行&操作并以十六进制获得结果:

40003019 & FE000000 => 40000000

我尝试将十六进制字符串转换为字节数组并执行个人
字节和导致字节的字节,在这种情况下,我分别得到4个字节。我正在寻找直接Hex结果。

我该怎么做?

var byteResult = new byte[4];
var byteArray1 = StringToByteArray("40003019");
var byteArray2 = StringToByteArray("FE000000");
for(int i = 0 ; i< 4; i++)
{
   byteResult[i] = (byte)(byteArray1[i]  & byteArray1[i]);
}

public static byte[] StringToByteArray(string hex)
{
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

1 个答案:

答案 0 :(得分:3)

转换(转换为整数),计算(按位和 - &),转换(返回字符串):

  string left = "40003019";
  string right = "FE000000";

  string result = 
    (Convert.ToUInt32(left, 16) & Convert.ToUInt32(right, 16)).ToString("X8");

一般情况下(长串可以是UInt64范围)

private static int CharToByte(char value) {
  if (value >= '0' && value <= '9')
    return value - '0';
  else if (value >= 'a' && value <= 'f')
    return value - 'a' + 10;
  else if (value >= 'A' && value <= 'F')
    return value - 'A' + 10;
  else
    return -1;
}

private static string BitwiseAnd(String left, String right) {
  // left and right can have different lengths
  int n = Math.Min(left.Length, right.Length);

  StringBuilder sb = new StringBuilder(n);

  for (int i = 0; i < n; ++i) {
    int v = CharToByte(left[left.Length - n + i]) & 
            CharToByte(right[right.Length - n + i]);

    sb.Append(v.ToString("X1"));
  }

  return sb.ToString();
}

...

string left = "40003019";
string right = "FE000000";

string result = BitwiseAnd(left, right);