바이트 []를 해당 텍스트 형식으로 변환하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/812716

  •  03-07-2019
  •  | 
  •  

문제

형식을 모르기 때문에 도움을 요청하는 것이 무엇인지 모르겠지만 사진이 있습니다.

바이트 [] 배열이 있습니다. 아래의 해당 형식으로 어떻게 변환합니까 (오른쪽)?

Alt Text http://img512.imageshack.us/img512/3548/48667724.jpg

평범한 ascii가 아닙니다.

도움이 되었습니까?

해결책

사용 b.ToString("x2") 바이트 값을 두 문자 16 진수 문자열로 포맷합니다.

ASCII 디스플레이의 경우 값이 일반 인쇄용 문자에 해당하는지 확인하고 다음과 같은 경우 변환하십시오.

if (b >= 32 && b <= 127) {
   c = (char)b;
} else {
   c = '.';
}

또는 짧은 :

c = b >= 32 && b <= 127 ? (char)b : '.';

배열에서 수행하려면 :

StringBuilder builder = new StringBuilder();
foreach (b in theArray) {
   builder.Append(b >= 32 && b <= 127 ? (char)b : '.');
}
string result = builder.ToString();

다른 팁

바이트 배열을 가져 와서 텍스트로 변환하고 싶은 것처럼 들립니다 (특정 범위 외부의 문자를 대체합니다. "."에스)

static public string ConvertFromBytes(byte[] input)
{
    StringBuilder output = new StringBuilder(input.Length);

    foreach (byte b in input)
    {
        // Printable chars are from 0x20 (space) to 0x7E (~)
        if (b >= 0x20 && b <= 0x7E)
        {
            output.Append((char)b);
        }
        else
        {
            // This isn't a text char, so use a placehold char instead
            output.Append(".");
        }
    }

    return output.ToString();
}

또는 linqy 확장 방법 (정적 확장 클래스 내부) :

static public string ToPrintableString(this byte[] bytes)
{
    return Encoding.ASCII.GetString
           (
              bytes.Select(x => x < 0x20 || x > 0x7E ? (byte)'.' : x)
                   .ToArray()
           );
}

(당신은 그것을 좋아한다고 부를 수 있습니다 string printable = byteArray.ToPrintableString();)

이것은 모든 인코딩 일 수 있습니다 ...이 테스트 스크립트를 시도하여 어떤 인 인쇄를 확인하십시오.

Bl8s

다음은 스크립트입니다.

byte[] b = new byte[] {0x42, 0x6C, 0x38, 0x73 };
foreach (EncodingInfo ei in Encoding.GetEncodings())
{
     Console.WriteLine("{0} - {1}", ei.GetEncoding().GetString(b), ei.Name);
}

편집 2018 : 코드를 훨씬 더 효율적으로 만들고 다른 문제를 해결하기 위해 기능을 처음부터 다시 작성하십시오. 이제 선택적으로 시작 오프셋과 바이트 수 (시작)를 표시 할 수있는 바이트 수를 지정할 수 있습니다.


오프셋 번호 및 왼쪽 및 오른쪽 디스플레이를 포함하여 전체 메모리 디스플레이를 원한다면 다음과 같이 할 수 있습니다. (32 바이트 너비)

/// <summary> Returns a String where the specified bytes are formatted in a
/// 3-section debugger-style aligned memory display, 32-bytes per line </summary>
public static unsafe String MemoryDisplay(byte[] mem, int i_start = 0, int c = -1)
{
    if (mem == null)
        throw new ArgumentNullException();
    if (i_start < 0)
        throw new IndexOutOfRangeException();
    if (c == -1)
        c = mem.Length - i_start;
    else if (c < 0)
        throw new ArgumentException();
    if (c == 0)
        return String.Empty;

    char* pch = stackalloc Char[32];       // for building right side at the same time
    var sb = new StringBuilder((c / 32 + 1) * 140);            // exact pre-allocation

    c += i_start;
    for (int i = i_start & ~0x1F; i < c;)
    {
        sb.Append(i.ToString("x8"));
        sb.Append(' ');

        do
        {
            if (i < i_start || i >= c)          // non-requested area, or past the end
            {
                sb.Append("   ");   
                pch[i & 0x1F] = ' ';
            }
            else
            {
                var b = mem[i];
                sb.Append(b.ToString("x2") + " ");
                pch[i & 0x1F] = non_monospace(b) ? '.' : (Char)b;
            }
        }
        while ((++i & 0x1F) != 0);

        sb.Append(' ');
        sb.AppendLine(new String(pch, 0, 32));
    }
    return sb.ToString();
}

이 코드는 다음 도우미를 사용하여 오른쪽 부분의 '점'으로 표시되어야하는 문자를 결정합니다.

static readonly ulong[] _nmb =
{
    0x00000000ffffe7ffUL,
    0x8000000000000000UL,
    0x00002000ffffffffUL,
    0x0000000000000000UL,
};

static bool non_monospace(byte b) => (_nmb[b >> 6] & 1UL << b) != 0;

위의 함수의 출력은 다음과 같습니다 (문자 너비는 138 개의 열이며 오른쪽으로 스크롤하여 "사람이 읽을 수있는"부분을보십시오) :

00000000 47 49 46 38 39 61 0f 00 0f 00 91 ff 00 00 00 00 c0 c0 c0 ff ff 00 00 00 00 21 f9 04 01 00 00 01 GIF89a...................!......
00000020 00 2c 00 00 00 00 0f 00 0f 00 00 02 2c 8c 0d 99 c7 91 02 e1 62 20 5a 79 ea bd 00 6d 89 69 8a f8 .,..........,.......b Zy...m.i..
00000040 08 e5 a7 99 e9 17 9d ac 24 a2 21 68 89 1e ac b4 d9 db 51 ab da c8 8c 1a 05 00 3b                ........$.!h......Q.......;

시도 : encoding.default.getBytes

그래도 작동하지 않으면 지정할 수있는 다른 유형이 있습니다 (UTF-8, ASCII ...)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top