8

我正在从内存中读取一些东西(在字节数组中),然后我想对其进行转换,但结果类似于“wanteddata\0\0\0\0\0\0\0\0...”。我怎样才能把它剪成“wanteddata”?我不确定wanteddata 的大小,所以我给出了最大大小:14。我从内存中读取并转换的方式:

        String w="";
        ReadProcessMemory(phandle, bAddr, buffer, 14, out bytesRW);
        w = ASCIIEncoding.ASCII.GetString(buffer);
4

5 回答 5

12

大概,您想删除所有字符,包括第一个 '\0' 和之后的所有字符。Trim不会这样做。你需要做这样的事情:

int i = w.IndexOf( '\0' );
if ( i >= 0 ) w = w.Substring( 0, i );
于 2012-04-30T11:01:41.223 回答
5

如果数组确实是 ascii(每个字符一个字节),您可以通过在数组中搜索值 0 来找到 null

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);

这种方法会在一定程度上优化代码,而不是创建包含多个 '/0' 的字符串

于 2012-04-30T12:08:53.640 回答
2

The value of bytesRW is the number of bytes that were copied to the buffer as stated here. The GetString method has an overload that takes a position and a length. If you pass zero as your position and bytesRW as the length it should create a string containing the value you wanted.

于 2012-04-30T11:06:10.393 回答
2

您可以像下面的代码一样使用 LINQ。

Encoding.ASCII.GetString(buffer.TakeWhile(x => x != 0).ToArray());
于 2020-05-14T03:02:10.170 回答
1

根据 mortb 响应,我得到了:

public static class EncodingEx
{
    /// <summary>
    /// Convert a C char* to <see cref="string"/>.
    /// </summary>
    /// <param name="encoding">C char* encoding.</param>
    /// <param name="cString">C char* to convert.</param>
    /// <returns>The converted <see cref="string"/>.</returns>
    public static string ReadCString(this Encoding encoding, byte[] cString)
    {
        var nullIndex = Array.IndexOf(cString, (byte) 0);
        nullIndex = (nullIndex == -1) ? cString.Length : nullIndex;
        return encoding.GetString(cString, 0, nullIndex);
    }
}

...

// A call
Encoding.ASCII.ReadCString(buffer)

但是,调用Array.IndexOf是不同的。第二个参数必须是 a byte,实际上0是 aint并且不能在byte数组中找到。

于 2014-04-10T15:32:23.560 回答