문제

나는 직렬 포트의 전송 및 수신 데이터를 일부는 하드웨어에서는 8 비트 데이터입니다.고 싶으로 저장할 문자열을 비교를 용이하게,그리고 미리 설정 데이터로 저장된 문자열이나 육식에서는 xml 파일이다.내가 찾는 것에만 사용하는 경우 인코딩이 있습니다.기본는 ANSI 인코딩 한 다음 8 비트 데이터로 변환이 제대로 쉽게 뒤집을 수 있습니다.ASCII 인코딩이만 작품에 대한 7 비트 데이터 및 UTF8 또는 UTF7 지 않는 잘 작동하기 때문에,너무 나는 일부를 사용하여 문자에서 1-255.인코딩이 있습니다.기본 될 것이지만 내가 읽은 MSDN 는 그에 따라 OS 코드페이지를 설정을 의미하는,그것을 다르게 작동 할 수 있는 다른 코드 페이지로 구성되어 있습니다.내가 사용하는 GetBytes()및 GetString 광범위하게 사용하여 인코딩 하는 것과 같은 안전 장치 및 휴대용 방법을 모든 시간에서 모든 구성이 있습니다.어떤 아이디어나 제안이 더 나은 이?

도움이 되었습니까?

해결책

Latin-1 일명 ISO-8859-1 일명 codepage28591 유용한 코드 페이지로 이 시나리오에 대한,그것으로도 값의 범위에서 128-255 변경되지 않습니다.다음과 같은 교환할 수 있:

Encoding.GetEncoding(28591)
Encoding.GetEncoding("Latin1")
Encoding.GetEncoding("iso-8859-1")

다음 코드는 사실을 보여 줍니다에 대한 라틴어 1 과는 달리,인코딩이 있습니다.기본적으로 모든 문자는 0-255 범위에 매핑되는 변경되지 않은:

static void Main(string[] args)
{

    Console.WriteLine("Test Default Encoding returned {0}", TestEncoding(Encoding.Default));
    Console.WriteLine("Test Latin1 Encoding returned {0}", TestEncoding(Encoding.GetEncoding("Latin1")));
    Console.ReadLine();
    return;
}

private static bool CompareBytes(char[] chars, byte[] bytes)
{
    bool result = true;
    if (chars.Length != bytes.Length)
    {
        Console.WriteLine("Length mismatch {0} bytes and {1} chars" + bytes.Length, chars.Length);
        return false;
    }
    for (int i = 0; i < chars.Length; i++)
    {
        int charValue = (int)chars[i];
        if (charValue != (int)bytes[i])
        {
            Console.WriteLine("Byte at index {0} value {1:X4} does not match char {2:X4}", i, (int) bytes[i], charValue);
            result = false;
        }
    }
    return result;
}
private static bool TestEncoding(Encoding encoding)
{
    byte[] inputBytes = new byte[256];
    for (int i = 0; i < 256; i++)
    {
        inputBytes[i] = (byte) i;
    }

    char[] outputChars = encoding.GetChars(inputBytes);
    Console.WriteLine("Comparing input bytes and output chars");
    if (!CompareBytes(outputChars, inputBytes)) return false;

    byte[] outputBytes = encoding.GetBytes(outputChars);
    Console.WriteLine("Comparing output bytes and output chars");
    if (!CompareBytes(outputChars, outputBytes)) return false;

    return true;
}

다른 팁

왜 그냥의 배열을 사용하여 바이트까요?그것도의 인코딩에 문제가 당신을 가능성이 고통을 텍스트로 접근 방식이다.

나는 당신이 사용해야하는 바이트 배열을 대신 합니다.비교를 위해 사용할 수 있는 몇 가지 방법은 다음과 같다:

static bool CompareRange(byte[] a, byte[] b, int index, int count)
{
    bool res = true;
    for(int i = index; i < index + count; i++)
    {
        res &= a[i] == b[i];
    }
    return res;
}

를 사용하여 히브리어의 코드페이지에 대한 Windows-1255.8 비트입니다.
인코딩 enc=Encoding.서 getencoding("windows-1255");

I missunderstod 할 때 쓴"1-255",를 refereing 하는 문자 코드페이지 1255.

당신이 사용할 수 있습 base64 인코딩을 변환하는 바이트는 문자열하고 다시.문제 없이 가진 코드페이지 또는 이상의 문자가 방법,그리고 더 많은 공간에 효율적인보다 육.

byte[] toEncode; 
string encoded = System.Convert.ToBase64String(toEncode);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top