将字符串位转换为字符串char

将字符串位转换为字符串char

本文介绍了将字符串位转换为字符串char,反之亦然,可以转换为ASCII C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

请你能帮我解决一下C#中的代码将字符串转换为字符串字符串,反之亦然,可以用ASCII格式来表示

例如:

bitstring =00111111101101010011111101101111001111111110110110011111101101111

resultstring =?μ?o?Û?o

并将其反转......



如果最好的话,你可以更正我的代码吗?



我尝试了什么:



拳头:

hello,
Please can you help me about code in C# to converting string bit to string char or vice versa,can out to ASCII
for example:
bitstring ="0011111110110101001111110110111100111111110110110011111101101111"
resultstring ="?µ?o?Û?o"
and reversing its...

Can you correct my code if it is the best?

What I have tried:

fist:

string result = "";
            while (value.Length > 0)
            {   var first8 = value.Substring(0, 8);
                value = value.Substring(8);
                var number = Convert.ToInt64(first8, 2);
                result += (char)number;







second






second

string S = "";
            byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
            for (int i = 0; i < asciiBytes.Length; i++)
                for (int j = 0; j < 8; j++)
                {
                    S += (asciiBytes[i] & 0x80) > 0 ? "1" : "0";
                    asciiBytes[i] <<= 1;
                }
            return S;

推荐答案

private string CharStringFromBitStringLittleEndian(string s)
    {
    StringBuilder sb = new StringBuilder(s.Length / 8 + 1);
    byte temp = 0;
    byte bit = 1;
    foreach (char c in s)
        {
        if (c == '1') temp |= bit;
        bit <<= 1;
        if (bit == 0)
            {
            sb.Append((char)temp);
            bit = 1;
            temp = 0;
            }
        }
    if (bit != 1) sb.Append((char)temp);
    return sb.ToString();
    }
private string CharStringFromBitStringBigEndian(string s)
    {
    StringBuilder sb = new StringBuilder(s.Length / 8 + 1);
    byte temp = 0;
    byte bit = 128;
    foreach (char c in s)
        {
        if (c == '1') temp |= bit;
        bit >>= 1;
        if (bit == 0)
            {
            sb.Append((char)temp);
            bit = 128;
            temp = 0;
            }
        }
    if (bit != 1) sb.Append((char)temp);
    return sb.ToString();
    }


int value = 219;
string binary = Convert.ToString(value, 2).PadLeft(8, '0');



2。)自制


2.) Self made

int value = 219;
StringBuilder sb = new StringBuilder(8);
while(value > 0)
{
	int mod= value % 2;
        if (mod == 0)
        {
        	sb.Insert(0, "0");
        }
	else
        {
        	sb.Insert(0, "1");
        }
        value /= 2;
}
string binary = sb.ToString().PadLeft(8, '0');





注意

注意,您正在使用Unicode,其中一个字符具有16位,而您的示例假设使用8位字符。



Note
Take care, you are working with Unicode for which a character has 16bit while your example assumes using 8 bit character.


这篇关于将字符串位转换为字符串char,反之亦然,可以转换为ASCII C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:57