首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

bitset崩溃,该怎么解决

2013-08-01 
bitset崩溃byte testBytes[5]{0x1,0x2,0x3,0x4,0x0} //vc环境下std::string strHelp((char*)testBytes)

bitset崩溃
  byte testBytes[5]={0x1,0x2,0x3,0x4,0x0}; //vc环境下

std::string strHelp((char*)testBytes);
#if 1
int nTemp=strHelp.length();//nTemp==4 ?
#endif
std::bitset<40> temp2(strHelp);//崩溃 



template<class _Elem,
class _Tr,
class _Alloc>
explicit bitset(const basic_string<_Elem, _Tr, _Alloc>& _Str,
_BITSET_SIZE_TYPE _Pos = 0)
{// construct from [_Pos, ...) elements in string
_Construct(_Str, _Pos,
basic_string<_Elem, _Tr, _Alloc>::npos, (_Elem)'0');
}

最终导致

void _Xinv() const
{// report invalid string element in bitset conversion
_THROW(invalid_argument, "invalid bitset<N> char");
}
抛出异常



需求: 用bitset模版类去操作字节数组testBytes!



[解决办法]

byte testBytes[5]={0x1,0x2,0x3,0x4,0x0}; //vc环境下

std::string strHelp((char*)testBytes);
#if 1
int nTemp=strHelp.length(); //nTemp==4 ?
#endif
std::bitset<40> temp2(strHelp); //崩溃
 

你要构造一个什么样的bitset?
使用string类型构造bitset时,string中应该只有字符'0'和'1’,'0'表示该位为0,‘1'表示该位为1。你的string中的四个字符全都是非法字条。
[解决办法]
If any characters examined in str are not zero or one, it throws std::invalid_argument.
[解决办法]
引用:
用bitset模版类去操作字节数组testBytes!,这是需求,

由于bitset 的构造函数 的版本 只有3个吧, 其中一个是 std::string

所以我才想,用string来过渡,没想到崩溃了。

怎么解决呢?

我想用bitset去操作testBytes这个字节数组里的某些位!!!


用什么方法来处理字节数组中的二进制位,这是属于实现的范畴,怎么会是需求呢?
“用bitset模版类去操作字节数组testBytes”,那么需要从字节数组构造出正确的bitset、对bitset进行操作、然后还要用bitset中的数据去更改字节数组。这样做还不如自己写个类去直接操作字节数组中的二进制位更简单。

如果你一定要用字节数组中的二进制位构造bitset,只能向下面这样:

    byte testBytes[5]= {0x1,0x2,0x3,0x4,0x0};



    std::bitset<40> temp2;
    unsigned int n = 0;
    for( unsigned int i = 0; i < 5; ++ i)
    {
        for( unsigned int j = 0; j < 8; ++ j)
        {
            temp2[n] = testBytes[i] >> j;
            ++ n;
        }
    }



[解决办法]
bitset一点也不实用,理解原理了自己实现一个类似的把

热点排行
Bad Request.