简体   繁体   English

std :: bitset中的可变位长<size>

[英]Variable bit length in std::bitset<size>

I'm not sure how to properly explain this, but I'm looking for a way to automatically set the size or number of the bitset<size> automatically 我不知道如何正确地解释这一点,但我正在寻找一种方式来自动设置sizenumber的中bitset<size>自动

Example

cout << bitset<8>(7) << endl;

outputs with a fixed number of bits 具有固定位数的输出

0000 0111

I want to automatically output with variable number of bits like outputting 111 and 11001 instead of using the fixed bits. 我想自动以可变位数输出,例如输出11111001而不是使用固定位数。

Basically I want to cut the 0 's in front when it's not used 基本上我想在不使用时将前面的0切掉

That's actually two questions in one. 这实际上是两个问题合而为一。 The first is how to trim the output a given bitset (ie remove the leading 0 's), the second how to reduce the output to a given size. 第一个是如何将输出调整为给定的位集(即删除前导的0 ),第二个是如何将输出减小为给定的大小。

As your interested only in the ostream output, for both it should be quite appropriate to use the bitset::to_string() conversion function, followed by an application of string::substr . 由于您只对ostream输出感兴趣,因此对于这两者,使用bitset::to_string()转换函数,然后再应用string::substr ,应该是非常合适的。

With this, for your example -- where it seems you want to retain 7 bits -- you would get: 以此为例,在您似乎想要保留7位的情况下,您将获得:

std::cout << std::bitset<8>{}.to_string().substr(1) << std::endl;  //removes the first bit 

You can combine that with a method to find the first set bit in order to construct the trim function. 您可以将其与方法结合起来以找到第一个设置位,以构造trim功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM