【问题标题】:How to break up integer into different variables?如何将整数分解为不同的变量?
【发布时间】:2019-03-06 02:43:22
【问题描述】:

我正在尝试将程序的最终结果进一步分解为 4 个部分。该程序将十六进制数转换为二进制数。我想把二进制数分成4个不同的部分。这些部分是 2、7、3、4。例如,将 0100000110001001 分解为 01|0000011|000|1001。我将把每个部分分配给变量 n1、n2、n3 和 n4。最终结果将是 n1=01、n2=0000011、n3=000 和 n4=1001。最好的方法是什么?我目前正在使用 c++,但如果更容易,可以切换到其他东西。谢谢

【问题讨论】:

  • 最好的方法是打开a good C++ book 并学习如何使用 C++ 位运算符来完成此任务。
  • Shift 和and,shift 和and

标签: c++ binary hex


【解决方案1】:

您可以结合使用>>(右移运算符)和&(布尔和运算符)来完成此操作。

#include <iostream>
#include <bitset>

int main(){

  int i = 0b0100000110001001;
  int n4 = i & 0b1111; 
  std::cout << "n4 = " << std::bitset<4>(n4) << '\n';
  i = i >> 4;
  int n3 = i & 0b111; 
  std::cout << "n3 = " << std::bitset<3>(n3) << '\n';
  i = i >> 3;
  int n2 = i & 0b1111111; 
  std::cout << "n2 = " << std::bitset<7>(n2) << '\n';
  i = i >> 7;
  int n1 = i & 0b11; 
  std::cout << "n1 = " << std::bitset<2>(n1) << '\n';

}

输出:

n4 = 1001
n3 = 000
n2 = 0000011
n1 = 01

【讨论】:

    【解决方案2】:

    好吧,您可以将二进制数解析为字符串,然后使用子字符串来获取 4 个数字部分。您可能对左零有疑问,它将被 int 变量丢弃。 我是用 C# 制作的。

    class Program
    {
        static void Main(string[] args)
        {
            string binaryNumber = "0100000110001001"; // your binary number to string
            int n1 = Convert.ToInt32(binaryNumber.Substring(0, 2));
            int n2 = Convert.ToInt32(binaryNumber.Substring(2, 7));
            int n3 = Convert.ToInt32(binaryNumber.Substring(9, 3));
            int n4 = Convert.ToInt32(binaryNumber.Substring(12, 4));
    
            string xn1 = n1.ToString().PadLeft(2, '0');
            string xn2 = n1.ToString().PadLeft(7, '0');
            string xn3 = n1.ToString().PadLeft(3, '0');
            string xn4 = n1.ToString().PadLeft(4, '0');
    
            Console.WriteLine("Numbers in INT variables (without left zeros)");
            Console.WriteLine($"1 Section (2):{n1}");
            Console.WriteLine($"2 Section (7):{n2}");
            Console.WriteLine($"3 Section (3):{n3}");
            Console.WriteLine($"4 Section (4):{n4}");
    
            Console.WriteLine("Numbers in STRING variables (with left zeros)");
            Console.WriteLine($"1 Section (2):{xn1}");
            Console.WriteLine($"2 Section (7):{xn2}");
            Console.WriteLine($"3 Section (3):{xn3}");
            Console.WriteLine($"4 Section (4):{xn4}");
            Console.ReadKey();
        }
    }
    

    希望对你有帮助!

    【讨论】:

    • 在转换为字符串然后解析字符串将起作用时,AND 和右移将在很短的时间内将数字切掉。
    猜你喜欢
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 2017-08-11
    • 1970-01-01
    • 2013-03-21
    • 2015-03-09
    相关资源
    最近更新 更多