M
M
miXtik7892021-12-03 11:24:36
ASP.NET
miXtik789, 2021-12-03 11:24:36

I can't convert characters to byte, how to make it work?

There is a code that converts string to byte:
byte[] data = Encoding.Unicode.GetBytes(message);
And that decrypts:

int bytes = 0; // количество полученных байтов
                        byte[] data = new byte[256]; // буфер для получаемых данных

                        do
                        {
                            bytes = handler.Receive(data);
                            builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                        }
                        while (handler.Available > 0);

Everything works fine with text.
But if you enter a message, say "@#$^@",
then in the end there will be a void, how to make it work with characters?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
ayazer, 2021-12-03
@miXtik789

var str = "test12!#@<смайлик>";

var utf16bytes = Encoding.Unicode.GetBytes(str);
var utf16reversed = Encoding.Unicode.GetString(utf16bytes); #test12!#@<смайлик>

you are confusing something somewhere, check your handler and how and in what encoding you send the data. the same difference in BE/LE between machines can lead to funny bugs. Well, in general - as you do - you can't do it. If you have "<smiley>" on 256 CHARACTER (ie a surrogate that consists of 2 real characters), but you will have an error during decoding. Therefore, at a minimum, you need to use a stateful encoder (var enc = Encoding.Unicode.GetEncoder(); ...). Well, or implement it yourself by checking char.IsLowSurrogate/char.IsHighSurrogate.
UPD: even the toaster has a problem with surrogates, instead of <smiley> it should have been U+1F60A ( https://www.compart.com/en/unicode/U+1F60A )

F
freeExec, 2021-12-03
@freeExec

Because Encoding.Unicode- this is UTF-16 and in it just the text @#$^@is not equivalent to the same in bytes (you can try to convert this string to bytes yourself). Most likely you need to use UTF-8 encoder.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question