[英]C# - Is there no simple way to concatenate hex and ASCII into a single string
In Python I'm able to concatenate both hex and ascii into a single string, then send it to the device I'm trying to control 在Python中,我可以将hex和ascii都连接为一个字符串,然后将其发送到我要控制的设备
_startTransmit = "\x02"
_channel = 7
command_string = _startTransmit + "PGM:" + str(_channel) + ";"
try:
written = conn.write(command_string.encode('utf-8'))
This SO Answer makes it appear building a byte array is the only way to do it in C# 这样的答案使得在C#中构建字节数组是唯一的方法
So, it appears there is no similar way to concatenate hex and ascii in C# as there is in Python. 因此,似乎没有像Python中那样在C#中连接十六进制和ascii的方法。 Am I correct?
我对么?
I'd look at using the string interpolator operator $ before the "string": 我想看看在“字符串”之前使用字符串插入器运算符$:
var _startTransmit = (char)0x02; //ints can be written in 0xFF format in the source code and cast to char e.g. (char)0x41 is a capital A
var _channel = 7;
var command_string = $"{_startTransmit}PGM:{_channel};"
The last line is syntactic sugar for: 最后一行是语法糖,用于:
var command_string = string.Format("{0}PGM:{1};", _startTransmit, _channel);
The things in {brackets} can have format specifiers, eg pad out the _channel to 4 chars with leading spaces, zeroes etc {_channel:0000}
- see https://docs.microsoft.com/en-us/dotnet/api/system.string.format?view=netframework-4.8 {括号}中的内容可以具有格式说明符,例如,将_channel填充为前导空格,零等的4个字符,
{_channel:0000}
-请参见https://docs.microsoft.com/zh-cn/dotnet/api/ system.string.format?view = netframework-4.8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.