无法从单词中提取啃咬

Unable to extract nibbles out of a word

本文关键字:提取 单词中      更新时间:2023-10-16

我正在尝试从 4 位二进制字符串中提取 16 位,即从单词中蚕食 谁能告诉我这个程序有什么问题?

#include <sstream>
#include <iomanip>
#include <math.h>
#include<iostream>
using namespace std;
int main()
{
    std::string aBinaryIPAddress = "1100110011001100";
    std::string digit0 = aBinaryIPAddress & 0x0f;
    cout << "digit0 : " << digit0 << endl;
    std::string digit1 = (aBinaryIPAddress >>  4) 0x0f;
    cout << "digit1 : " << digit1 << endl;
    std::string digit2 = (aBinaryIPAddress >>  8) 0x0f;
    cout << "digit2 : " << digit2 << endl;
    std::string digit3 = (aBinaryIPAddress >> 12) 0x0f;
    cout << "digit3 : " << digit3 << endl;
    return 0;
}

我收到以下错误:

 changes.cpp: In function `int main()':
 changes.cpp:117: error: invalid operands of types `char*' and `int' to binary `
 operator>>'
 changes.cpp:117: error: parse error before numeric constant

如果你正在操作一个string,你应该使用substr,而不是"移位和掩码"技术:&>>运算符是未为字符串和int定义的。

以下是使用substr的方法:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string aBinaryIPAddress = "0101100111101101";
    size_t len = aBinaryIPAddress.size();
    for (int i = 0 ; i != 4 ; i++) {
        cout << "Digit " << i << ": " << aBinaryIPAddress.substr(len-4*(i+1), 4) << endl;
    }
    return 0;
}

这打印

Digit 0: 1101
Digit 1: 1110
Digit 2: 1001
Digit 3: 0101

在 ideone 上演示。

如果需要四个单独的变量,请"展开"循环,如下所示:

string d0 = aBinaryIPAddress.substr(len-4, 4);
string d1 = aBinaryIPAddress.substr(len-8, 4);
string d2 = aBinaryIPAddress.substr(len-12, 4);
string d3 = aBinaryIPAddress.substr(len-16, 4);

您不能像这样从整数转换为字符串。您可以使用字符串流:

#include <iomanip>
......
std::string convert_int_to_hex_stiring(int val) {
  std::stringstream ss;
  ss << std::hex << val;
  return val;
}

在使用上述函数之前,您必须从输入字符串的各个部分读取整数。问题是没有在字符串上定义按位运算。

aBinaryIPAddress的类型应该是数字而不是字符串

类似的东西

unsigned int aBinaryIPAddress = 0b1100110011001100;

应该工作

您有一个包含 16 个字符的 std::string 对象,每个字符的值为 '0''1' 。如果你想看看从那里取的"蚕食",只需拉出你需要的 4 个字符组:

std::string digit0 = aBinaryIPAddress.substr(12,4);
std::cout << digit0 << 'n';

这只是文本操作;如果你想获取值,将digit0中的字符转换为数值是很简单的(也是一个有用的练习)。

很明显,问题出在这样的语句中

std::string digit0 = aBinaryIPAddress & 0x0f;

你明白 std::string 不是一个数字吗?!