How to convert a string with pairs of numbers to an array of bytes without converting in C#

1 Answer

0 votes
using System;
using System.Text;

public class Program
{
    public static void PrintByteArray(byte[] bytes) {
        var sb = new StringBuilder("byte[] = ");
        
        foreach (var b in bytes) {
            sb.Append(b + ", ");
        }

        Console.WriteLine(sb.ToString());
    }

    public static void Main()
    {
        string str = "97987099304825";
        byte[] bytes = new byte[str.Length / 2];

        for (int i = 0; i <= str.Length - 1; i += 2) {
            bytes[i / 2] = Convert.ToByte(str.Substring(i, 2));
        }

        Console.WriteLine(Encoding.UTF8.GetString(bytes));

        PrintByteArray(bytes);
    }
}


/*
run:
  
abFc0
byte[] = 97, 98, 70, 99, 30, 48, 25, 
  
*/

 



answered May 28, 2024 by avibootz

Related questions

...