-1

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

   _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#

So, it appears there is no similar way to concatenate hex and ascii in C# as there is in Python. Am I correct?

Norm Schaeffer
  • 411
  • 3
  • 9
  • 1
    It's entirely possible, but irrelevant, that Python _could_ be doing something similar under the covers. There's nothing stopping you from implementing one of the methods in your linked Answer as an [extension method](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) to greatly simplify your C# syntax. – krillgar May 29 '19 at 17:37
  • 1
    in c# `var _startTransmit = (char)0x02; var _channel = 7; var command_string = $"{_startTransmit}PGM:{_channel};"` is hardly longer/more complex? – Caius Jard May 29 '19 at 17:43
  • 1
    That python code _doesn't_ send a string, it sends a [byte literal](https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal) - `b'\x02PGM:7;'` – stuartd May 29 '19 at 17:49
  • @CaiusJard - very helpful, your suggestion is simple and elegant. Thank you. – Norm Schaeffer May 29 '19 at 17:52
  • @krillgar - I was thinking that Python is probably doing more in the background than I know. – Norm Schaeffer May 29 '19 at 17:53

1 Answers1

2

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://learn.microsoft.com/en-us/dotnet/api/system.string.format?view=netframework-4.8

Caius Jard
  • 72,509
  • 5
  • 49
  • 80