Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert and add a String to List<byte>?

Tags:

string

c#

list

byte

I have a string which I want to convert into bytes (using the encoding.getbytes() function properly) and then the bytes that result from the conversion, add them to a List.

How can I do this? I've thought about doing a for and converting each character in the string and add it one by one to the list but I would like to know if there is a more efficient way of doing this.

like image 344
Fideon Avatar asked Dec 03 '25 23:12

Fideon


2 Answers

Can't you just convert the GetBytes array to a list?

List<byte> byteList = Encoding.Default.GetBytes(inputString).ToList();

Or pass the array to List's constructor:

List<byte> byteList = new List<Byte>(Encoding.ASCII.GetBytes(str));
like image 104
CC Inc Avatar answered Dec 06 '25 14:12

CC Inc


class Program
{
    static void Main(string[] args)
    {
        String str = "Kiran Bheemarti";

        List<byte> bytes = Encoding.ASCII.GetBytes(str).ToList();

        Console.Read();
    }
}
like image 28
Kiran Bheemarti Avatar answered Dec 06 '25 13:12

Kiran Bheemarti