无法从单词中提取啃咬
Unable to extract nibbles out of a word
我正在尝试从 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 不是一个数字吗?!
相关文章:
- 当您在此单词中搜索单词时调整字符数组的大小?
- 计算单词中的音节数,但考虑到单词中彼此相邻的任何元音都算作一个音节
- 如何使用Qt删除单词中的表行
- 模式匹配文本并提取C++中的数据
- C++ - 使用结构数据类型将单词中的单个小写字符更改为大写,反之亦然
- 查找并提取文件中的某个值
- 使用 Python 和正则表达式提取源代码中的C++注释
- 提取字符串中的随机单词
- 在 C++ 中,仅使用递归来提取向量中的最大元素
- 计算单词中的字母
- 如何在C 中不带有弦乐和strtok的情况下拆分字符串(提取单词)
- 如何提取字符串中的特定值
- 如何提取字符串中的整数?
- 从微妙的问题中提取单词
- 提取 C++ 中分量之间的子字符串
- 在单词中移动字母n次
- 从C中的文件中提取单词
- C++编写一个从段落中提取单词的函数
- 无法从单词中提取啃咬
- 提取c++输出中某个单词前面的值