表示字节值>;127英寸.Net字符串
本文关键字:127英寸 Net 字符串 gt 字节 表示 | 更新日期: 2023-09-27 18:26:50
我正在.Net中使用字符串编写一些二进制协议消息,除一种特殊情况外,它基本上是。
我试图发送的信息是:
String cmdPacket = "'xFD'x0B'x16MBEPEXE1.";
myDevice.Write(Encoding.ASCII.GetBytes(cmdPacket));
(为了帮助解码,这些字节是253、11、22,然后是ASCII字符:"MBEPEXE1."
)。
除了当我执行Encoding.ASCII.GetBytes
时,0xFD
显示为字节0x3F
(值253更改为63)。
(我应该指出,'x0B
和'x16
被正确地解释为Hex 0B
和Hex 16
)
我也试过Encoding.UTF8
和Encoding.UTF7
,但都没有用。
我觉得可能有一种简单的方法可以在字符串中表达128以上的值,并将其转换为字节,但我错过了它
有什么指导吗?
忽略您正在做的事情是好是坏,编码ISO-8859-1
将其所有字符映射到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和Unicode的前256个代码点被合并。
或者一种简单快速的方法将string
转换为byte[]
(具有unchecked
和checked
变体)
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;
}
ASCII是一个7位代码。高阶位过去用作奇偶校验位,因此"ASCII"可以具有偶数、奇数或无奇偶校验。您可能会注意到0x3F(十进制63)是ASCII字符?
。这就是CLR的ASCII编码将非ASCII八位字节(大于0x7F/decimal 127的八位字节)转换为的值。原因是0x80–范围内的代码点没有标准的ASCII字符表示;0xFF。
C#字符串内部是UTF-16编码的Unicode。如果你关心的是字符串的字节值,并且你知道字符串实际上是Unicode代码点在U+0000
到U+00FF
范围内的字符,那么这很容易。Unicode的前256个代码点(0x00–0xFF)、Unicode块C0控件和基本拉丁语(''x00-''x7F)以及C1控件和拉丁语补充(''x80-''xFF)是"正常"ISO-8859-1字符。像这样一个简单的咒语:
String cmdPacket = "'xFD'x0B'x16MBEPEXE1.";
byte[] buffer = cmdPacket.Select(c=>(byte)c).ToArray() ;
myDevice.Write(buffer);
会给你想要的byte[]
,在这种情况下是
// 'xFD 'x0B 'x16 M B E P E X E 1 .
[ 0xFD , 0x0B , 0x16 , 0x4d , 0x42 , 0x45, 0x50 , 0x45 , 0x58 , 0x45 , 0x31 , 0x2E ]
使用LINQ,您可以执行以下操作:
String cmdPacket = "'xFD'x0B'x16MBEPEXE1.";
myDevice.Write(cmdPacket.Select(Convert.ToByte).ToArray());
编辑:添加解释
首先,您认识到您的字符串实际上只是一个字符数组。您想要的是一个"等效"的字节数组,其中每个字节对应一个字符。
要获得数组,必须将原始数组的每个字符"映射"为新数组中的一个字节。为此,您可以使用内置的System.Convert.ToByte(char)
方法。
一旦描述了从字符到字节的映射,就可以通过映射将输入字符串投影到数组中。
希望能有所帮助!
我使用Windows-1252,因为它似乎给字节带来了最大的冲击
并且与所有.NET字符串值兼容
您可能想要注释掉ToLower
这是为了与SQL字符(单字节)兼容而构建的
namespace String1byte
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
String8bit s1 = new String8bit("cat");
String8bit s2 = new String8bit("cat");
String8bit s3 = new String8bit("'xFD'x0B'x16MBEPEXE1.");
HashSet<String8bit> hs = new HashSet<String8bit>();
hs.Add(s1);
hs.Add(s2);
hs.Add(s3);
System.Diagnostics.Debug.WriteLine(hs.Count.ToString());
System.Diagnostics.Debug.WriteLine(s1.Value + " " + s1.GetHashCode().ToString());
System.Diagnostics.Debug.WriteLine(s2.Value + " " + s2.GetHashCode().ToString());
System.Diagnostics.Debug.WriteLine(s3.Value + " " + s3.GetHashCode().ToString());
System.Diagnostics.Debug.WriteLine(s1.Equals(s2).ToString());
System.Diagnostics.Debug.WriteLine(s1.Equals(s3).ToString());
System.Diagnostics.Debug.WriteLine(s1.MatchStart("ca").ToString());
System.Diagnostics.Debug.WriteLine(s3.MatchStart("ca").ToString());
}
}
public struct String8bit
{
private static Encoding EncodingUnicode = Encoding.Unicode;
private static Encoding EncodingWin1252 = System.Text.Encoding.GetEncoding("Windows-1252");
private byte[] bytes;
public override bool Equals(Object obj)
{
// Check for null values and compare run-time types.
if (obj == null) return false;
if (!(obj is String8bit)) return false;
String8bit comp = (String8bit)obj;
if (comp.Bytes.Length != this.Bytes.Length) return false;
for (Int32 i = 0; i < comp.Bytes.Length; i++)
{
if (comp.Bytes[i] != this.Bytes[i])
return false;
}
return true;
}
public override int GetHashCode()
{
UInt32 hash = (UInt32)(Bytes[0]);
for (Int32 i = 1; i < Bytes.Length; i++) hash = hash ^ (UInt32)(Bytes[0] << (i%4)*8);
return (Int32)hash;
}
public bool MatchStart(string start)
{
if (string.IsNullOrEmpty(start)) return false;
if (start.Length > this.Length) return false;
start = start.ToLowerInvariant(); // SQL is case insensitive
// Convert the string into a byte array
byte[] unicodeBytes = EncodingUnicode.GetBytes(start);
// Perform the conversion from one encoding to the other
byte[] win1252Bytes = Encoding.Convert(EncodingUnicode, EncodingWin1252, unicodeBytes);
for (Int32 i = 0; i < win1252Bytes.Length; i++) if (Bytes[i] != win1252Bytes[i]) return false;
return true;
}
public byte[] Bytes { get { return bytes; } }
public String Value { get { return EncodingWin1252.GetString(Bytes); } }
public Int32 Length { get { return Bytes.Count(); } }
public String8bit(string word)
{
word = word.ToLowerInvariant(); // SQL is case insensitive
// Convert the string into a byte array
byte[] unicodeBytes = EncodingUnicode.GetBytes(word);
// Perform the conversion from one encoding to the other
bytes = Encoding.Convert(EncodingUnicode, EncodingWin1252, unicodeBytes);
}
public String8bit(Byte[] win1252bytes)
{ // if reading from SQL char then read as System.Data.SqlTypes.SqlBytes
bytes = win1252bytes;
}
}
}