根据C#中的索引值替换字节

时间:2018-04-18 15:32:24

标签: c# hex byte

我正在尝试编写一个控制台应用程序,它将数据作为输入并将其拆分为两个

示例:如果我传递值0x00000000A0DB383E作为输入,我的输出应如下所示:

var LowerValue = 0x00000000A0DB0000 (last 2 bytes 383E (index 14-17) replaced with 0000)
var UpperValue = 0x000000000000383E (middle 2 bytes A0DB (index 10-13) replaced with 0000)

到目前为止,我已尝试过以下但不知道如何继续进行。任何帮助将受到高度赞赏

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace SplitFunction
{
    class Program
    {
        static void Main(string[] args)
        {
        byte[] rawValue = BitConverter.GetBytes(0x00000000A0DB383E);
        SplitData(rawValue);
        Console.ReadKey();
        }

        public static byte[] SplitDta(byte[] input)
        {
            byte[] lowerValues =  new byte[8];
            Array.Copy(input, 0, lowerValues, 4, 4);
            foreach(var lowerValue in lowerValues)
                Console.WriteLine(lowerValue);
            return lowerValues;
        }
    }
}

1 个答案:

答案 0 :(得分:5)

而不是复制&将各个数组元素归零,使用掩码直接创建新数组。像这样:

long input = 0x0000000A0DB383EL;

byte[] rawValue = BitConverter.GetBytes(input);
byte[] lowValue = BitConverter.GetBytes(input & 0x000000000000FFFF);
byte[] highValue = BitConverter.GetBytes(input & 0x00000000FFFF0000);

如果你希望值按高字节到低字节的顺序 - 然后反转它们

byte[] rawValue = Array.Reverse(BitConverter.GetBytes(input));
byte[] lowValue = Array.Reverse(BitConverter.GetBytes(input & 0x000000000000FFFF));
byte[] highValue = Array.Reverse(BitConverter.GetBytes(input & 0x00000000FFFF0000));

如果你只想要长值而不是数组

long lowValue = input & 0x000000000000FFFF;
long highValue = input & 0x00000000FFFF0000;