P
P
Popou2022-02-24 07:39:32
.NET
Popou, 2022-02-24 07:39:32

How to store string as bytes?

The encoding of the string is utf-8, I know how this encoding works, and what C# methods can work with it.

I have an array of bytes, and here's the thing, these bytes themselves are just instructions, like push on a stack, add two elements on a stack, and so on and so forth. But how do I push a string? I know that of course the link to the string is pushed into the stack, and not the string itself, but c# does it for me. And the question is, how to determine that the line is over? Use for this a specific set of bytes or a character (in principle, the same as bytes) and define this as the end of the line? Or in the beginning to declare line length? Then this is also a problem, so to start one English "a" it will take 6 bytes = 1 for the command to push the line, 4 for the size, and 1 byte for the line itself, I know it looks ridiculous that I cling to each byte, but I'm just wondering how to do it right.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2022-02-24
@Popou

I don't understand what you want to achieve. What you are saying is low level programming, you don't need C# for that. Take C/C++ and enjoy direct memory manipulation.
In general, there are two approaches to strings. The first one used Pascal: its length is stored in the zero byte of the string. Since Pascal used a one-byte encoding (ANSI), this was enough to store strings up to 255 bytes long. You can, in principle, use both 2 and 4 bytes. And it worked well.
The second approach is the C++ approach where the string ends with '\0' (zero-terminated string). Here, too, there are subtleties, mainly related to the fact that when determining the length of a string, you need to remember that '\0' is not included in its length. There is also a potential error associated with line overflow and damage to the memory blocks following it.
Choose which approach you like best.

D
Didar Kamiljanow, 2022-02-24
@DidarCoder

In order to store strings in bytes, a MemoryStream can come to your rescue:

byte[] data = new byte[255];
MemoryStream memory  = new MemoryStream(data);

StreamWriter writer = new StreamWriter(memory);
StreamReader reader = new StreamReader(memory);

With writer and reader you can do string I/O!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question