Search code examples
swiftprotocolscontrol-characters

How to add / remove 1 Byte of control character(s) STX & EXT in swift


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


Solution

  • 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)
    }