如何从 c# 中的字符串中获取位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/655830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:05:20  来源:igfitidea点击:

How could I get the bits from a string in c#?

c#

提问by Xaisoft

If I had the following string "Blue Box", how could I get the bits that make up the string in c# and what datatype would I store it in.

如果我有以下字符串“Blue Box”,我如何在 c# 中获取组成字符串的位以及我将它存储在什么数据类型中。

If I do just the letter "o", I get 111 as the bytes and 111 as the bits. Is it chopping off the 0's and if I do "oo", I get 111 for each o in the byte array, but for the bits, I get the value 28527. Why?

如果我只做字母“o”,我会得到 111 作为字节和 111 作为位。它是否切断了 0,如果我执行“oo”,我会为字节数组中的每个 o 得到 111,但对于位,我得到值 28527。为什么?

采纳答案by John Rasch

If you want the bits in a string format, you could use this function:

如果你想要字符串格式的位,你可以使用这个函数:

public string GetBits(string input)
{
    StringBuilder sb = new StringBuilder();
    foreach (byte b in Encoding.Unicode.GetBytes(input))
    {
        sb.Append(Convert.ToString(b, 2));
    }
    return sb.ToString();
}

If you use your "Blue Box" example you get:

如果您使用“蓝盒”示例,您会得到:

string bitString = GetBits("Blue Box");
// bitString == "100001001101100011101010110010101000000100001001101111011110000"

回答by Jim H.

That depends on what you mean by "bits". Are you talking about the ASCII representation? UTF8? UTF16? The System.Text.Encoding namespace should get you started.

这取决于你所说的“位”是什么意思。你在谈论 ASCII 表示吗?UTF8?UTF16?System.Text.Encoding 命名空间应该可以帮助您入门。

回答by Scott Weinstein

You could do the following:

您可以执行以下操作:

byte[] bytes = System.Text.UTF8Encoding.Default.GetBytes("Blue Box");
BitArray bits = new System.Collections.BitArray(bytes);