1

I am writing a code, where I want to add 1 byte of STX at the start of the string & 1 byte of ETX at the end of the swift string.

Not sure how to do it.

Example:

<1B>---<3B>--<1B>-<1B>---<3B>--<1B>
<STX><String><ETX><STX><String><ETX>

Where 1B = 1 Byte & 3B = 3 Byte

STX= Start of Text
ETX= End of Text

Control Characters Reference: enter link description here

spt025
  • 2,134
  • 2
  • 20
  • 26

1 Answers1

1

You could just use the special characters in string litterals. Considering that the ASCII control codes STX and ETX have no special escape character, you could use their unicode scalar values 0x02 and 0x03.

Directly in the string literal

You can construct the string using a string literal, if needed with interpolation:

let message="\u{02}...\u{03}\u{02}xyz\u{03}"

You can cross-check printing the numeric value of each byte :

for c in message.utf8 {
    print (c)
}

Concatenating the string

You can also define some string constants:

let STX="\u{02}"
let ETX="\u{03}"

And build the string by concatenating parts. In this example, field1 and field2 are string variables of arbitrary length that are transformed to exactly 3 character length:

let message2=STX+field1.padding(toLength: 3, withPad: " ", startingAt:0)+ETX+STX+field2.padding(toLength: 3, withPad: " ", startingAt:0)+ETX
print (message2)
for c in message2.unicodeScalars {
    print (c, c.value)
}
Christophe
  • 68,716
  • 7
  • 72
  • 138
  • Q: If I need this to be converted to byte stream e.g. et STX=UInt8(ascii: "\u{02}"), does it still remain a valid STX character? (During print I can see, it just being converted to 2) – spt025 Jun 27 '22 at 05:25
  • @spt025 STX is indeed a binary value of 2. It is remains therefire a valid STX character, although it is not printable and the receiver of the byte stream needs to be aware of the use if non printable control characters. What may be more problematic is the length of the string between the control characters if you use non ascii characters, since utf8 may encode them on several bytes. – Christophe Jun 27 '22 at 06:22