C# 从字符串中读取两个字节

发布于 2024-11-07 18:48:54 字数 199 浏览 0 评论 0原文

嗨,

我正在以十六进制读取一个文件并将其存储在一个字符串中,我需要做的是一次读取两个字符,所以说我有一个包含

313233343536373839

的字符串,我需要读取 31 ,然后是32 后面是 33

我对 C# 和一般编程很陌生,我的书没有任何内容,我找不到一个可以很好地解释它的例子,如果你能建议我,我将不胜感激!

HI,

I'm reading a file in as hex and storing it in a string, what I need to do is then read in two chars at a time so say i have a string that contains

313233343536373839

I would need to read in 31 followed by 32 followed by 33

I'm new to c# and programming in general, my book has nothing on it and I can't find an example that explains it well for me, if you could advise me I would be greatful!

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

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

发布评论

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

评论(2

逆流 2024-11-14 18:48:54

如果您想将此十六进制字符串表示形式转换为字节数组,您可以使用以下命令:

string str = "313233343536373839";
byte[] buffer = Enumerable
    .Range(0, str.Length)
    .Where(x => x % 2 == 0)
    .Select(x => Convert.ToByte(str.Substring(x, 2), 16))
    .ToArray();

If you want to convert this hex string representation into a byte array you could use the following:

string str = "313233343536373839";
byte[] buffer = Enumerable
    .Range(0, str.Length)
    .Where(x => x % 2 == 0)
    .Select(x => Convert.ToByte(str.Substring(x, 2), 16))
    .ToArray();
多孤肩上扛 2024-11-14 18:48:54
string myString = "313233343536373839";

for (int i=0; i<myString.Length; i+=2)
{
    string myChars = myString.Substring(i, 2);
    // do something with myChars here ...
}

当达林发帖时,我正在发帖。没想过要这样做。干得好,达林!

string myString = "313233343536373839";

for (int i=0; i<myString.Length; i+=2)
{
    string myChars = myString.Substring(i, 2);
    // do something with myChars here ...
}

Was in the middle of posting this when Darin posted. Hadn't thought about doing it that way. Nice work Darin!

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