문제

나는있다 byte[] 내가 알려진 파일에서로드 된 배열은 UTF-8. 일부 디버깅 코드에서는 문자열로 변환해야합니다. 이것을 할 라이너 하나가 있습니까?

표지 아래에서는 할당이어야하며 Memcopy, 그것이 구현되지 않더라도 가능해야합니다.

도움이 되었습니까?

해결책

string result = System.Text.Encoding.UTF8.GetString(byteArray);

다른 팁

이 변환을 수행하는 방법은 적어도 4 가지입니다.

  1. 인코딩의 GetString
    , 그러나 해당 바이트에 ASCII 문자가없는 경우 원래 바이트를 되 찾을 수 없습니다.

  2. Bitconverter.tostring
    출력은 "-"구분 문자열이지만 문자열을 바이트 배열로 다시 변환하는 .NET 내장 메소드는 없습니다.

  3. 변환 .tobase64String
    사용하여 출력 문자열을 바이트 배열로 쉽게 변환 할 수 있습니다. Convert.FromBase64String.
    참고 : 출력 문자열에는 '+', '/'및 '='가 포함될 수 있습니다. 문자열을 URL에서 사용하려면 명시 적으로 인코딩해야합니다.

  4. httpserveritility.urltokenencode
    사용하여 출력 문자열을 바이트 배열로 쉽게 변환 할 수 있습니다. HttpServerUtility.UrlTokenDecode. 출력 문자열은 이미 URL 친화적입니다! 단점은 필요하다는 것입니다 System.Web 프로젝트가 웹 프로젝트가 아닌 경우 어셈블리.

전체 예 :

byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters

string s1 = Encoding.UTF8.GetString(bytes); // ���
byte[] decBytes1 = Encoding.UTF8.GetBytes(s1);  // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results

string s2 = BitConverter.ToString(bytes);   // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
    decBytes2[i] = Convert.ToByte(tempAry[i], 16);
// decBytes2 same as bytes

string s3 = Convert.ToBase64String(bytes);  // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes

string s4 = HttpServerUtility.UrlTokenEncode(bytes);    // gsjqFw2
byte[] decBytes4 = HttpServerUtility.UrlTokenDecode(s4);
// decBytes4 same as bytes

인코딩을 모를 때 바이트 배열에서 문자열로 변환하는 일반적인 솔루션 :

static string BytesToStringConverted(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        using (var streamReader = new StreamReader(stream))
        {
            return streamReader.ReadToEnd();
        }
    }
}

정의:

public static string ConvertByteToString(this byte[] source)
{
    return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}

사용 :

string result = input.ConvertByteToString();

변환 a byte[] a string 간단 해 보이지만 모든 종류의 인코딩은 출력 문자열을 엉망으로 만들 수 있습니다. 이 작은 기능은 예상치 못한 결과없이 작동합니다.

private string ToString(byte[] bytes)
{
    string response = string.Empty;

    foreach (byte b in bytes)
        response += (Char)b;

    return response;
}

사용 (byte)b.ToString("x2"), 출력 b4b5dfe475e58b67

public static class Ext {

    public static string ToHexString(this byte[] hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return string.Empty;

        var s = new StringBuilder();
        foreach (byte b in hex) {
            s.Append(b.ToString("x2"));
        }
        return s.ToString();
    }

    public static byte[] ToHexBytes(this string hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return new byte[0];

        int l = hex.Length / 2;
        var b = new byte[l];
        for (int i = 0; i < l; ++i) {
            b[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
        }
        return b;
    }

    public static bool EqualsTo(this byte[] bytes, byte[] bytesToCompare)
    {
        if (bytes == null && bytesToCompare == null) return true; // ?
        if (bytes == null || bytesToCompare == null) return false;
        if (object.ReferenceEquals(bytes, bytesToCompare)) return true;

        if (bytes.Length != bytesToCompare.Length) return false;

        for (int i = 0; i < bytes.Length; ++i) {
            if (bytes[i] != bytesToCompare[i]) return false;
        }
        return true;
    }

}

클래스 유니 코드 코딩도 있습니다.

ByteConverter = new UnicodeEncoding();
string stringDataForEncoding = "My Secret Data!";
byte[] dataEncoded = ByteConverter.GetBytes(stringDataForEncoding);

Console.WriteLine("Data after decoding: {0}", ByteConverter.GetString(dataEncoded));

대안으로 :

 var byteStr = Convert.ToBase64String(bytes);

바이트 어레이를 변환하기위한 LINQ 1 라이너 byteArrFilename 파일에서 순수한 ASCII C 스타일의 제로 종료 문자열로 읽으십시오. 이전 아카이브 형식의 파일 색인 테이블과 같은 것을 읽는 데 편리합니다.

String filename = new String(byteArrFilename.TakeWhile(x => x != 0)
                              .Select(x => x < 128 ? (Char)x : '?').ToArray());

나는 사용한다 '?' 여기에서 순수한 ASCII가 아닌 경우 기본 문자로, 물론 변경할 수 있습니다. 감지 할 수 있는지 확인하려면 사용하십시오. '\0' 대신, 이후 TakeWhile 처음에는이 방법으로 구축 된 문자열에 '\0' 입력 소스의 값.

BitConverter 클래스를 사용하여 a를 변환 할 수 있습니다 byte[] 에게 string.

var convertedString = BitConverter.ToString(byteAttay);

문서화 BitConverter 클래스는 변형 될 수 있습니다 MSDN

내 아는 한, 주어진 답변 중 어느 것도 Null 종료로 올바른 동작을 보장하지 않습니다. 누군가가 다르게 보여줄 때까지 나는 다음 방법으로 이것을 처리하기 위해 내 자신의 정적 수업을 썼습니다.

// Mimics the functionality of strlen() in c/c++
// Needed because niether StringBuilder or Encoding.*.GetString() handle \0 well
static int StringLength(byte[] buffer, int startIndex = 0)
{
    int strlen = 0;
    while
    (
        (startIndex + strlen + 1) < buffer.Length // Make sure incrementing won't break any bounds
        && buffer[startIndex + strlen] != 0       // The typical null terimation check
    )
    {
        ++strlen;
    }
    return strlen;
}

// This is messy, but I haven't found a built-in way in c# that guarentees null termination
public static string ParseBytes(byte[] buffer, out int strlen, int startIndex = 0)
{
    strlen = StringLength(buffer, startIndex);
    byte[] c_str = new byte[strlen];
    Array.Copy(buffer, startIndex, c_str, 0, strlen);
    return Encoding.UTF8.GetString(c_str);
}

그 이유 startIndex 내가 구체적으로 작업하고있는 예에서 나는 구문 분석해야했다. byte[] 널 종료 된 줄의 배열로. 간단한 경우에 안전하게 무시할 수 있습니다

Hier는 인코딩을 귀찮게 할 필요가없는 결과입니다. 네트워크 클래스에서 사용하여 이진 객체를 문자열로 보냅니다.

        public static byte[] String2ByteArray(string str)
        {
            char[] chars = str.ToArray();
            byte[] bytes = new byte[chars.Length * 2];

            for (int i = 0; i < chars.Length; i++)
                Array.Copy(BitConverter.GetBytes(chars[i]), 0, bytes, i * 2, 2);

            return bytes;
        }

        public static string ByteArray2String(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / 2];

            for (int i = 0; i < chars.Length; i++)
                chars[i] = BitConverter.ToChar(bytes, i * 2);

            return new string(chars);
        }

선택한 답변을 준수하면 .NET35 또는 .NET35 CE를 사용하는 경우 첫 바이트의 인덱스와 디코딩 할 바이트 수를 지정해야합니다.

string result = System.Text.Encoding.UTF8.GetString(byteArray,0,byteArray.Length);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top