You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串转二进制后,如何去除前导0011或替换为0000?

提取数字字符二进制的后四位并实现累加

你的问题本质是处理ASCII数字字符的二进制表示:数字字符'0'-'9'的ASCII码范围是48-57,对应二进制就是00110000到00111001,所以前四位固定为0011,后四位才是对应数字的二进制值。以下是几种解决方法:

方法1:直接截取二进制字符串的后四位

既然你已经把二进制补全到8位,直接用Substring(4)截取从第5位开始的后四位即可:

Console.WriteLine("Enter a number: ");
string response = Console.ReadLine();

foreach (char c in response)
{
    string full8BitBinary = Convert.ToString(c, 2).PadLeft(8, '0');
    string lastFourBits = full8BitBinary.Substring(4);
    Console.WriteLine($"Char: {c}   {lastFourBits}");
}

方法2:利用ASCII码特性转换(更可靠)

数字字符减去'0'的ASCII值(48)就能直接得到对应的数字,再把这个数字转成4位二进制,避免字符串截取的潜在问题:

Console.WriteLine("Enter a number: ");
string response = Console.ReadLine();

foreach (char c in response)
{
    // 先判断是否为数字字符,避免非数字输入出错
    if (char.IsDigit(c))
    {
        int digitValue = c - '0';
        string fourBitBinary = Convert.ToString(digitValue, 2).PadLeft(4, '0');
        Console.WriteLine($"Char: {c}   {fourBitBinary}");
    }
}

实现累加功能

如果需要累加这些数字的数值,直接用上面得到的digitValue累加即可(因为后四位二进制对应的十进制值就是数字本身):

Console.WriteLine("Enter a number: ");
string response = Console.ReadLine();
int total = 0;

foreach (char c in response)
{
    if (char.IsDigit(c))
    {
        int digitValue = c - '0';
        total += digitValue;
        string fourBitBinary = Convert.ToString(digitValue, 2).PadLeft(4, '0');
        Console.WriteLine($"Char: {c}   {fourBitBinary}");
    }
}

Console.WriteLine($"累加结果: {total}");

内容的提问来源于stack exchange,提问作者user3763812

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 14:52:42