简体   繁体   中英

How to Assign a bitset to an unsigned char vector?

I am using an unsigned char vector which has some hex values.

   std::vector<unsigned char> sync;
   sync.push_back(0x50);
   sync.push_back(0x51);
   sync.push_back(0x52);
   sync.push_back(0x53);

Then, using a bitset I "morph" the sync[3] to an 8 bit representation.This is because I need to corrupt/toggle any random bit in it.

    srand(time(NULL));
    int bitsetIndex= random()%8; 
    std::bitset<8> manipulator(v[3]); //v is the vector argument which takes "sync" vector
                                      //by reference 
    manipulator.flip(bitsetIndex);

Since, I am passing my vector by reference, I wanted to make changes to it. ie whatever changes I have made to my bitset, I wanted to commit it to the vector too. However, I am not sure how to convert a bitset to an unsigned char and how to assign it to my vector, in order to update my vector sync .

Call manipulator.to_ulong() . (The narrowing conversion to your unsigned char will be harmless.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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