将用户输入(字节格式)转换为字节数组

我猜我正在寻找的是将a转换string[]为a byte[],而实际上没有将其内容转换string[]为字节,因为它们已经是字节了。




我有以下代码:


public static bool isHex(String hex) {

    if(hex.Substring(0, 2) == "0x")

        hex = hex.Substring(2, (hex.Length - 2));

    return Regex.IsMatch(hex, @"\A\b[0-9a-fA-F]+\b\Z");

}


static void Main(string[] args) {

    Console.Write("Input bytes: ");

    String input = Console.Readline();


    String[] valueArray = input.Split(new string[] { "\\x" }, StringSplitOptions.None);

    for(int i = 0; i > valueArray.Length; i++)

        if(!isHex(valueArray[i]))

            usage(args[1] + " is not valid hex", 6);

}

它获取用户输入,并检查其是否为有效的十六进制。


假设用户输入\x00\xff\x12,我想知道如何将其转换为字节数组。


但是,我不想将字符串转换为字节,因为字节在字符串中(\ x 00 \ x ff \ x 12),但是我想将这些值插入字节数组中。


我不想数组元素自行字节转换(即["00", "FF", "12"]至["30", "30", "66", "66", "31", "32"],因为["00", "FF", "12"]是有效的十六进制)。


幕布斯7119047
浏览 189回答 1
1回答

胡子哥哥

检查一下,我修改了您的代码,您需要的字节数组是 byteArray顺便说一句,您的循环条件是错误的,应该是 i < valueArray.Length我不确定这是不是你想要的using System;using System.Collections.Generic;using System.Globalization;namespace ConsoleApplication{&nbsp; &nbsp; class Program&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.Write("Input bytes: ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String input = Console.ReadLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String[] valueArray = input.Split(new string[] { "\\x" }, StringSplitOptions.RemoveEmptyEntries);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<byte> byteArray = new List<byte>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < valueArray.Length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int ret = -1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string hex = valueArray[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (hex.StartsWith("0x"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hex = hex.Substring(2, hex.Length - 2);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!Int32.TryParse(hex, NumberStyles.HexNumber, null, out ret) || ret < 0 || ret > 0xff) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine("{0} is not valid hex", valueArray[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; byteArray.Add((byte)ret);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP