簡體   English   中英

c#中如何將帶有字節的字符串轉換為字節數組

[英]How to convert the string with Byte to byte array in c#

我有一個字節格式的字符串,如下所示

var string="22-74-68-64-62-32-75-74-71-53-5A-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22"

將其轉換為字節數組為

byte[] arr=[22-74-68-64-62-32-75-74-71-53-5A-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22]
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string input = "22-74-68-64-62-32-75-74-71-53-5A-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22";

        //Split string by '-'
        string[] spl = input.Split('-');

        //Parse bytes and add them to a list
        List<byte> buf = new List<byte>();
        foreach(string s in spl) {
            buf.Add(byte.Parse(s, System.Globalization.NumberStyles.HexNumber));
        }

        //Convert list to byte[]
        byte[] bytes = buf.ToArray();

        //Print byte[] into console
        foreach(byte b in bytes)
            Console.WriteLine(b.ToString("X2"));
    }
}

網絡小提琴

如果輸入不是由破折號分隔的完美字節字符串,則上述代碼將導致異常。 如果您不期待完美的輸入,則必須像這樣使用byte.TryParse

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string input = "22-74-68-64-62-32-75-74-71-53-5A-XX-wrgererh-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22";

        //Split string by '-'
        string[] spl = input.Split('-');

        //Parse bytes and add them to a list
        List<byte> buf = new List<byte>();
        byte tb;
        foreach(string s in spl) {
            if(byte.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out tb))
                buf.Add(tb);
        }

        //Convert list to byte[]
        byte[] bytes = buf.ToArray();

        //Print byte[] into console
        foreach(byte b in bytes)
            Console.WriteLine(b.ToString("X2"));
    }
}

網絡小提琴

你可以使用Linq把它弄得非常整潔

byte[] arr = input.Split('-').Select(i => byte.Parse(i, System.Globalization.NumberStyles.HexNumber)).ToArray();

使用Convert.ToByte稍微簡潔一點

var bytes = input.Split('-')
                 .Select(x => Convert.ToByte(x,16))
                 .ToArray();

其他資源

ToByte(字符串,Int32)

指定基數中數字的字符串表示形式轉換為等效的 8 位無符號整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM