bithift操作问题

时间:2017-01-09 20:14:30

标签: c# algorithm byte bit-shift

我试图从当地的标准中实现哈希。 但它在简单的换档功能中返回错误的结果。我尝试了转移信息:

byte[] test = Hash.StringToByteArrayFastest("EFCDAB8967452301");
Console.WriteLine(ToHex(Hash.ShLo(test)));
Console.WriteLine(ToHex(Hash.ShHi(test)));

我希望得到:

ShLo : 77E6D5C4B3A2918016
ShHi : DF9B5712CE8A460216

但得到这个:

ShLo : f7e6d5c4b3a29100
ShHi : de9b5713cf8a4602

这是我的代码

public static byte[] ShHi(byte[] B)
{
    return BitConverter.GetBytes(BitConverter.ToUInt64(B, 0) << 1);
}
public static byte[] ShLo(byte[] B)
{
    return BitConverter.GetBytes(BitConverter.ToUInt64(B, 0) >> 1);
}
public static byte[] StringToByteArrayFastest(string hex)
{
    if (hex.Length % 2 == 1)
        throw new Exception("The binary key cannot have an odd number of digits");
    byte[] arr = new byte[hex.Length >> 1];
    for (int i = 0; i < hex.Length >> 1; ++i)
    {
        arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
    }
    return arr;
}
public static int GetHexVal(char hex)
{
    int val = (int)hex;
    return val - (val < 58 ? 48 : 55);
}
public static string ToHex(byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];
    byte b;
    for (int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
    {
        b = ((byte)(bytes[bx] >> 4));
        c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
        b = ((byte)(bytes[bx] & 0x0F));
        c[++cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
    }
    return new string(c);
}

1 个答案:

答案 0 :(得分:0)

public static string ToHex(byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];
    byte b;
    for (int bx = 0, cx = c.Length - 1; bx < bytes.Length; ++bx)
    {
        b = ((byte)(bytes[bx] & 0x0F));
        c[cx--] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
        b = ((byte)(bytes[bx] >> 4));
        c[cx--] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
    }
    return new string(c);
}
public static byte[] StringToByteArrayFastest(string hex)
{
    if (hex.Length % 2 == 1) throw new Exception("The binary key cannot have an odd number of digits");
    byte[] arr = new byte[hex.Length >> 1];
    for (int i = 0, j = arr.Length - 1; i < arr.Length; ++i)
    {
        arr[j--] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
    }
    return arr;
}