【问题标题】:How do i get all the bits present on odd positions in binary representation of integers?如何获得整数二进制表示中奇数位置上的所有位?
【发布时间】:2021-10-01 16:34:51
【问题描述】:

这些位从最左边的设置位开始从左到右枚举,即最高有效位。例如,77 的二进制表示为 1001101。二进制表示中第 1、第 3、第 5 和第 7 位的位分别为 1,0,1,1。

【问题讨论】:

    标签: c++ c++17 bit-manipulation bit


    【解决方案1】:

    Python:

    int_val = 77
    binary_val = bin(int_val)[2:]
    odd_pos_data = [ value for index,  value in enumerate(binary_val,1) if index % 2 != 0 ]
    print(odd_pos_data)
    

    结果:

    ['1', '0', '1', '1']
    

    This is how to do in C++:

    #include <iostream>
    #include <bitset>
    
    using namespace std;
    
    int main()
    {   
        int num ;
        cout<<"Enter value : \n";
        cin >> num;
        std::string binary = std::bitset<8>(num).to_string(); //to binary
        cout<<"Binary value : \n\n";
        std::cout<<binary<<"\n\n";
        std::cout<<"Odd Index values:\n";
         for (int i = 0; i < binary.length(); i++) {
            if(i % 2 != 0){
            cout<< binary[i]<< " ";
            }
        }
        return 0;
    }
    

    结果:

    【讨论】:

    • 是的!如果你能在 C++ 中做到这一点,那就太好了......
    • 你使用过python标签
    • 是的,这是一个错误
    • @varru15 我已经更新了我的 c++ 答案,试试看,如果有帮助就接受答案。
    猜你喜欢
    • 1970-01-01
    • 2018-03-17
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 2014-05-24
    相关资源
    最近更新 更多