我注意到虽然标准库有I / O操纵器以十进制,十六进制或八进制形式(std::dec
, std::hex
, std::oct
)打印数字,但它没有二进制数。
我将如何实现类似的二进制I / O操纵器?
反重复标记部分:我非常沮丧,我必须这样做,但我的问题几乎总是被标记为完全不同和无益的问题的重复。也许这会帮助人们远离错误的重复,并找到真正的副本,如果他们确实存在。
std::string to_binary(T value)
,void print_binary(T value)
,......)。以下是我到目前为止所抛出的内容,它仍然存在许多问题,而且我真的不明白发生了什么。我刚刚复制并修改了question Phil链接的解决方案。
#include <ios>
#include <iostream>
#include <locale>
int geti() {
static int i = std::ios_base::xalloc();
return i;
}
std::ostream& bin_manip(std::ostream& os) {
os.iword(geti()) = 1;
return os;
}
std::ostream& dec_manip(std::ostream& os) {
os.iword(geti()) = 0;
return os;
}
struct my_num_put : std::num_put<char> {
iter_type do_put(iter_type out, std::ios_base& str, char_type fill, long v) const {
bool binary_flag = str.iword(geti());
if (binary_flag) {
size_t width = 8 * sizeof(v);
for (size_t i = width - 1; i < width; --i) {
long bit = (((1 << i) & v) >> i) & 1;
out = std::num_put<char>::do_put(out, str, fill, bit);
}
return out;
}
else {
return std::num_put<char>::do_put(out, str, fill, v);
}
}
/*
iter_type do_put(iter_type s, std::ios_base& f, char_type fill, unsigned long v) const {
return std::num_put<char>::do_put(s, f, fill, v + f.iword(geti()));
}
*/
};
int main() {
std::cout.imbue(std::locale(std::locale(), new my_num_put)); // memory leak?
int v1 = 10;
long v2 = 11;
std::cout << bin_manip << v1 << std::endl << v2 << std::endl;
std::cout << dec_manip << v1 << std::endl << v2 << std::endl;
return 0;
}
输出如下:
0000000000000000000000000000000000000000000000000000000000001010
0000000000000000000000000000000000000000000000000000000000001011
10
11
我在这里看到的主要问题是处理各种类型时的代码重复。就像我一样,我只使用do_put
函数,该函数采用long
类型的值,不幸的是打印出比它们应该更宽的int
值。我试图模拟该函数,它完全消除了操纵器的效果,只需打印出10
和11
而不是它们的二进制表示。
另一个问题是,我不确定将每个1
和0
写入流的最佳方法是什么。现在我正在写它们似乎有问题,我真的想把它们写成单个字符。
最后,我不确定new
是否会造成内存泄漏,但valgrind告诉我它没有。