如何添加 /删除控制字符的1个字节STX&斯威夫特

发布于 2025-02-11 03:10:55 字数 507 浏览 1 评论 0 原文

我正在编写一个代码,我想在字符串& 1个字节 etx 在Swift String的末尾。

不知道该怎么做。

示例:

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

其中1b = 1个字节&amp; 3b = 3字节

STX= Start of Text
ETX= End of Text

控制字符参考:输入链接在这里

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绝情姑娘 2025-02-18 03:10:55

您可以只使用 STX 和 ETX 没有特殊的逃生字符,您可以使用其Unicode stallar值 0x02 0x03 < /代码>。

直接在字符串中,

您可以使用字符串字面的字符串构造字符串,如果需要,则可以插值:

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

您可以交叉检查打印每个字节的数字值:

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

串联字符串,

您也可以定义一些字符串常数:

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

并通过串联构建字符串部分。在此示例中, field1 field2 是任意长度的字符串变量,这些变量被转换为完全3个字符长度:

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

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)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文