programing

C # : 바이트 배열을 문자열로 변환하고 콘솔로 인쇄

goodcopy 2021. 1. 17. 11:54
반응형

C # : 바이트 배열을 문자열로 변환하고 콘솔로 인쇄


public void parse_table (BinaryReader inFile)
{
    바이트 [] idstring = inFile.ReadBytes (6);
    Console.WriteLine (Convert.ToString (idstring));
}

이것은 간단한 스 니펫입니다. 파일의 처음 6 바이트를 읽고이를 문자열로 변환합니다.

그러나 콘솔에 System.Byte[].

변환에 잘못된 클래스를 사용하고있을 수 있습니다. 무엇을 사용해야합니까? 결국 UTF-8로 인코딩 된 파일 이름을 구문 분석하고 동일한 방법을 사용하여 모든 파일 이름을 읽을 계획입니다.


실제로 :

    Console.WriteLine(Encoding.Default.GetString(value));

또는 특히 UTF-8의 경우 :

    Console.WriteLine(Encoding.UTF8.GetString(value));

나는 Test 클래스에 대한 입력으로 부호있는 바이트 배열 ( sbyte[])을 가지고있는 곤경에 처했고 이를 byte[]단순하게하기 위해 일반 바이트 배열 ( ) 로 바꾸고 싶었습니다 . 나는 Google 검색에서 여기에 도착했지만 Tom의 대답은 나에게 유용하지 않았습니다.

주어진 이니셜 라이저를 인쇄하는 도우미 메서드를 작성했습니다 byte[].

public void PrintByteArray(byte[] bytes)
{
    var sb = new StringBuilder("new byte[] { ");
    foreach (var b in bytes)
    {
        sb.Append(b + ", ");
    }
    sb.Append("}");
    Console.WriteLine(sb.ToString());
}

다음과 같이 사용할 수 있습니다.

var signedBytes = new sbyte[] { 1, 2, 3, -1, -2, -3, 127, -128, 0, };
var unsignedBytes = UnsignedBytesFromSignedBytes(signedBytes);
PrintByteArray(unsignedBytes);
// output:
// new byte[] { 1, 2, 3, 255, 254, 253, 127, 128, 0, }

출력은 유효한 C #이며 코드에 복사 할 수 있습니다.

완전성을 위해 다음과 같은 UnsignedBytesFromSignedBytes방법이 있습니다.

// http://stackoverflow.com/a/829994/346561
public static byte[] UnsignedBytesFromSignedBytes(sbyte[] signed)
{
    var unsigned = new byte[signed.Length];
    Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
    return unsigned;
}

이것은 불필요한 후행 ,문자를 추가하지 않는 Jesse Webbs 코드의 업데이트 된 버전입니다 .

public static string PrintBytes(this byte[] byteArray)
{
    var sb = new StringBuilder("new byte[] { ");
    for(var i = 0; i < byteArray.Length;i++)
    {
        var b = byteArray[i];
        sb.Append(b);
        if (i < byteArray.Length -1)
        {
            sb.Append(", ");
        }
    }
    sb.Append(" }");
    return sb.ToString();
}

이 메서드의 출력은 다음과 같습니다.

new byte[] { 48, ... 135, 31, 178, 7, 157 }

내 코드베이스에서 다음과 같은 간단한 코드를 사용했습니다.

static public string ToReadableByteArray(byte[] bytes)
{
    return string.Join(", ", bytes);
}

쓰다:

Console.WriteLine(ToReadableByteArray(bytes));

 byte[] bytes = { 1,2,3,4 };

 string stringByte= BitConverter.ToString(bytes);

 Console.WriteLine(stringByte);

linq 및 문자열 보간에 대한 재미를 위해 :

public string ByteArrayToString(byte[] bytes)
{
    if ( bytes == null ) return "null";
    string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
    return $"new byte[] {{ {joinedBytes} }}";
}

테스트 사례 :

byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();

산출:

new byte[] { 1, 2, 3, 4 }
null
new byte[] {  }

ReferenceURL : https://stackoverflow.com/questions/10940883/c-converting-byte-array-to-string-and-printing-out-to-console

반응형