Strange behavior when converting a byte from a text field into a byte array into characters?

I have a text box that I use to convert things like:

74 00 65 00 73 00 74 00

Back to the line, β€œtest” is said above, but for some reason, when I click the β€œConvert” button, it displays only the first letter β€œt” 74 00, and other byte arrays work just as expected, all the text is converted.

Here are two codes I tried that produce the same behavior, incorrectly converting the entire byte array back to word:

byte[] bArray = ByteStrToByteArray(iSequence.Text);
ASCIIEncoding enc = new ASCIIEncoding();
string word = enc.GetString(bArray);
iResult.Text = word + Environment.NewLine;

which uses the function:

private byte[] ByteStrToByteArray(string byteString)
{
    byteString = byteString.Replace(" ", string.Empty);
    byte[] buffer = new byte[byteString.Length / 2];
    for (int i = 0; i < byteString.Length; i += 2)
        buffer[i / 2] = (byte)Convert.ToByte(byteString.Substring(i, 2), 16);
    return buffer;
}

Another way that I used is:

string str = iSequence.Text.Replace(" ", "");
byte[] bArray = Enumerable.Range(0, str.Length)
                            .Where(x => x % 2 == 0)
                            .Select(x => Convert.ToByte(str.Substring(x, 2), 16))
                            .ToArray();
ASCIIEncoding enc = new ASCIIEncoding();
string word = enc.GetString(bArray);
iResult.Text = word + Environment.NewLine;

Tried to check the length to see if it was an iteration, and that was ...

, , , -, , , .

- , ? , , ?

+3
4

var bytes = new byte[] { 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00 };

ASCII- (Encoding.ASCII),

var result = Encoding.ASCII.GetString(bytes);
// result == "\x74\x00\x65\x00\x73\x00\x74\x00" == "t\0e\0s\0t\0"

Null \0? ​​ , Null.

, "test", ASCII, UTF-16LE (Encoding.Unicode).

var result = Encoding.Unicode.GetString(bytes);
// result == "\u0074\u0065\u0073\u0074" == "test"
+9

unicode ascii, . System.Text.Encoding.GetEncoding("codepage").GetString() . , .NET unicode... Soooooo.... , ( ), .. eof . .

+1

, VS2010. ,

string word = enc.GetString(bArray);

"t\0e\0s\0t".

iResult.Text = word + Environment.NewLine;

iResult.Text " t".

So, I thought that \ 0 is not a valid escape sequence, the compiler ignores everything after it. This may not be correct, but try removing all occurrences of 00 in the input string.

I am not in C #. I suggest this only because it is similar to C ++.

0
source

This works for me:

string outputText = "t\0e\0s\0t";
outputText = outputText.Replace("\0", " ");
0
source

All Articles