0

I want to convert string into ascii and storing it into byte array. I know the simplest way for this is

Encoding.ASCII.GestBytes

but what I want is

byte[] temp = new byte[];
temp = Encoding.ASCII.GestBytes("DEMO1");

Thus when I do

Console.WriteLine(temp[i])

it should print out 68 69 77 48 0 0 0 0 0 0 0 0 0 0 0 0 instead of 68 69 77 48

How can I achieve this?

1 Answer 1

1

Be aware that if the buffer is too much small, this will throw:

byte[] temp = new byte[10];
string str = "DEMO1";
Encoding.ASCII.GetBytes(str, 0, str.Length, temp, 0);

There is no easy way, compatible with UTF8, to handle it (because UTF8 has variable-length characters). For ASCII and other fixed length encodings you could:

byte[] temp = new byte[10];
string str = "DEMO1";
Encoding.ASCII.GetBytes(str, 0, Math.Min(str.Length, temp.Length), temp, 0);

Or, in general you could:

string str = "DEMO1";
byte[] temp = Encoding.ASCII.GetBytes(str);
Array.Resize(ref temp, 10);

and this would work even with UTF8.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.