本文介绍了防爆pressing字节值>在.net中的字符串127的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一些二进制协议消息在.NET中使用的字符串,它的大多的除了一个特定的情况下工作。

I'm writing some binary protocol messages in .Net using strings, and it mostly works, except for one particular case.

我想发送的消息是:

String cmdPacket = "\xFD\x0B\x16MBEPEXE1.";
myDevice.Write(Encoding.ASCII.GetBytes(cmdPacket));

(帮助去code,这些字节是253,11,22,然后是ASCII字符:。MBEPEXE1)。

除了当我这样做 Encoding.ASCII.GetBytes 是0xFD 出来为字节的0x3F (价值253更改为63)。

Except when I do the Encoding.ASCII.GetBytes, the 0xFD comes out as byte 0x3F(value 253 changed to 63).

(我要指出的是, \ X0B \ X16 是正确PTED为跨$ P $ 十六进制0B &安培; 十六进制16

(I should point out that the \x0B and \x16 are interpreted correctly as Hex 0B & Hex 16)

我也试过 Encoding.UTF8 Encoding.UTF7 ,都无济于事。

I've also tried Encoding.UTF8 and Encoding.UTF7, to no avail.

我觉得有可能是一个好简单的方法,上面的字符串128 EX preSS值,并将其转换为字节,但是我很想念它。

I feel there is probably a good simple way to express values above 128 in Strings, and convert them to bytes, but I'm missing it.

任何指导?

推荐答案

忽略,如果它是好还是坏你在做什么,编码 ISO-8859-1 映射所有它的字符以相同的code在统一字符code。

Ignoring if it's good or bad what you are doing, the encoding ISO-8859-1 maps all its characters to the characters with the same code in Unicode.

// Bytes with all the possible values 0-255
var bytes = Enumerable.Range(0, 256).Select(p => (byte)p).ToArray();

// String containing the values
var all1bytechars = new string(bytes.Select(p => (char)p).ToArray());

// Sanity check
Debug.Assert(all1bytechars.Length == 256);

// The encoder, you could make it static readonly
var enc = Encoding.GetEncoding("ISO-8859-1"); // It is the codepage 28591

// string-to-bytes
var bytes2 = enc.GetBytes(all1bytechars);

// bytes-to-string
var all1bytechars2 = enc.GetString(bytes);

// check string-to-bytes
Debug.Assert(bytes.SequenceEqual(bytes2));

// check bytes-to-string
Debug.Assert(all1bytechars.SequenceEqual(all1bytechars2));

维基

ISO-8859-1被合并为ISO / IEC 10646和统一code第一次256 code点。

或者一个简单而快速的方法来一个字符串转换为字节[] (用选中检查变体)

Or a simple and fast method to convert a string to a byte[] (with unchecked and checked variant)

public static byte[] StringToBytes(string str)
{
    var bytes = new byte[str.Length];

    for (int i = 0; i < str.Length; i++)
    {
        bytes[i] = checked((byte)str[i]); // Slower but throws OverflowException if there is an invalid character
        //bytes[i] = unchecked((byte)str[i]); // Faster
    }

    return bytes;
}

这篇关于防爆pressing字节值&GT;在.net中的字符串127的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:39