gpt4 book ai didi

c# - 如何在 C# 中将字符串转换为 "Null Terminated Byte Array"?

转载 作者:行者123 更新时间:2023-12-04 00:55:57 26 4
gpt4 key购买 nike

假设我的字符串是"John Doe"

如何将其转换为字节数组

目前我只有将字符串转换成字节数组的代码,但是如何将我变成空终止字节数组

byte[] bytes = Encoding.ASCII.GetBytes("John Doe");

提前致谢

最佳答案

无需深入了解您可能需要它的原因。我假设它用于串行端口、套接字或文件等。

你可以使用:

byte[] bytes = Encoding.ASCII.GetBytes("John Doe\0");

Demo here

如果你真的很无聊,你可以创建一个字符串或字节数组扩展方法:

public static string ToNullTerminatedString(this string source) 
=> source + '\0';

public static byte[] ToNullTerminatedArray(this byte[] source)
{
byte[] newArray = new byte[source.Length + 1];
source.CopyTo(newArray, 0);
return newArray;
}

关于c# - 如何在 C# 中将字符串转换为 "Null Terminated Byte Array"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62568665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com