【问题标题】:Bytes to Nibbles to Words to Bytes in C#C# 中的字节到半字节到字到字节
【发布时间】:2019-01-31 05:22:10
【问题描述】:

我需要一个 3 字节的数组

  • 将每个字节转换为半字节
  • 将 Byte_0.Nibble_0 + Byte_0.Nibble_1 + Byte_1.Nibble_2 添加为 WORD
  • 将 Byte_1.Nibble_0 + Byte_2.Nibble_1 + Byte_2.Nibble_2 添加为 WORD
  • 将每个 WORD 转换为字节数组

这是我尝试过的

 private static void GetBytesToNibbles(byte[] currentThree, out byte[] a, out byte[] b)
        {
            var firstLowerNibble = currentThree[0].GetNibble(0);
            var firstUpperNibble = currentThree[0].GetNibble(1);
            var secondLowerNibble = currentThree[1].GetNibble(0);
            var secondUpperNibble = currentThree[1].GetNibble(1);

            var thirdLowerNibble = currentThree[2].GetNibble(0);
            var thirdUpperNibble = currentThree[2].GetNibble(1);

            a= new byte[] {firstLowerNibble, firstUpperNibble, secondLowerNibble, 0x00};
            b= new byte[] {secondUpperNibble, thirdLowerNibble, thirdUpperNibble, 0x00};
        }

获取 Nibble 扩展:

 public static byte GetNibble<T>(this T t, int nibblePos)
            where T : struct, IConvertible
        {
            nibblePos *= 4;
            var value = t.ToInt64(CultureInfo.CurrentCulture);
            return (byte) ((value >> nibblePos) & 0xF);
        }

我做对了吗,如图所示?如果没有,任何人都可以帮助我提供正确的代码吗?

【问题讨论】:

  • “将每个 WORD 转换为字节数组” - 我希望 byte[2] 是结果,而不是 byte[4] 你有......你可能想澄清什么是实际的预期结果。跨度>
  • @AlexeiLevenkov 你是对的,这就是我需要做的。我需要 byte[2] 但填充 0000。不知道如何实现它。

标签: c# arrays byte word nibble


【解决方案1】:

这并不完美,但它会给你一个 4 字节的数组,你应该可以自己拆分。

图像令人困惑,因为它显示的是位数而不是示例值。我认为这就是您认为需要两个 4 字节数组的原因。

public static void Main()
{
    byte byte0 = 0x11;
    byte byte1 = 0x22;
    byte byte2 = 0x33;

    int low = BitConverter.ToInt32(new byte[]{byte0, byte1,0,0},0);
    int high = BitConverter.ToInt32(new byte[] {byte1, byte2,0,0},0);

    low = low & 0x0fff;
    high = high & 0xfff0;
    high = high << 12;
    int all = high | low;

    byte[] intBytes = BitConverter.GetBytes(all);

    for (int i = 0; i < intBytes.Length; i++)
    {
        Console.WriteLine(String.Format("{0:X2}", intBytes[i]));
    }
}

结果:

11 02 32 03

【讨论】:

  • 所以从这个 4 字节数组中,我将前两个作为一组,另外两个作为另一组?
猜你喜欢
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2021-03-27
相关资源
最近更新 更多