Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# byte[] to String showing don't cut after '\0'

Tags:

string

c#

byte

I'm reading something from memory (in byte array) and then i want to convert it, but result is something like "wanteddata\0\0\0\0\0\0\0\0...". How can i cut it to "wanteddata"? I'm not sure of size that wanteddata will have so i gave maximum size: 14. The way i read from memory and convert:

        String w="";
        ReadProcessMemory(phandle, bAddr, buffer, 14, out bytesRW);
        w = ASCIIEncoding.ASCII.GetString(buffer);
like image 741
Piotr Łużecki Avatar asked Apr 30 '12 10:04

Piotr Łużecki


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.


2 Answers

Presumably, you want to remove all chars including and after the first '\0'. Trim will not do this. You need to do something like this:

int i = w.IndexOf( '\0' );
if ( i >= 0 ) w = w.Substring( 0, i );
like image 199
Nick Butler Avatar answered Oct 02 '22 22:10

Nick Butler


If the array really is ascii (one byte per char), you can find null by searching array for value 0

String w="";
ReadProcessMemory(phandle, bAddr, buffer, 14, out bytesRW);
int nullIdx = Array.IndexOf(buffer, (byte)0);
nullIdx = nullIdx >= 0 ? nullIdx : buffer.Length;
w = ASCIIEncoding.ASCII.GetString(buffer, 0, nullIndex);

This approach would somewhat optimize the code, not creating strings that contains multiple '/0's

like image 27
mortb Avatar answered Oct 02 '22 22:10

mortb