如何字符串转换为空值终止吗? [英] How to convert string to null-terminated one?

查看:150
本文介绍了如何字符串转换为空值终止吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将简单的字符串转换为空值终止有一个

How to convert a simple string to a null-terminated one?

为例串:测试信息结果
以下是字节:

Example string: "Test message"
Here are the bytes:

54 65 73 74 20 6D 65 73 73 61 67 65

我需要字符串字节喜欢如下:

I need string with bytes like follows:

54 00 65 00 73 00 74 00 20 00 6D 00 65 00 73 00 73 00 61 00 67 00 65 00 00

我可以使用循环,但会过于丑陋的代码。我怎样才能让通过本地方法这一转换?

I could use loops, but will be too ugly code. How can I make this conversion by native methods?

推荐答案

它看起来像你想有一个空值终止的Unicode字符串。如果字符串存储在一个变量 STR ,这应该工作:

It looks like you want a null-terminated Unicode string. If the string is stored in a variable str, this should work:

var bytes = System.Text.Encoding.Unicode.GetBytes(str + "\0");



看到它运行。)

请注意所产生的阵列将在年底起零字节。这是因为,Unicode的使用两个字节表示字符。第一个零是在原字符串中的最后一个字符的一半,接下来的两个都是Unicode编码是如何空字符'\0 。 (换句话说,有一个使用我的代码比最初指定一个额外的空字符,但是这可能是你真正想要的东西。)

Note that the resulting array will have three zero bytes at the end. This is because Unicode represents characters using two bytes. The first zero is half of the last character in the original string, and the next two are how Unicode encodes the null character '\0'. (In other words, there is one extra null character using my code than what you originally specified, but this is probably what you actually want.)

这篇关于如何字符串转换为空值终止吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆