简体   繁体   中英

C++ convert 8 bit bitset to unsigned long, VS 2010 - not working

Below code works first two times thru and then on the third time the convert to ulong fails and gives me a 0XCF instead of 0xF3. Any idea what the problem is?? Seems like a bug in the VS 2010 to_long. binary '11110011' should convert to Hex F3! Here are the results when running debug under VS 2010.

1ST TIME bc_bit_char b'11000011' converts to k = x'000000c3'; 2ND TIME: bc_bit_char b'00111100' converts to k = x'0000003c' 3RD TIME: bc_bit_char b'11110011' converts to k = x'000000cf' WRONG! s/b x'000000f3'

    std::bitset<8> bc_bit_char (00000000);
    unsigned char bc_char=' ', bc_convert_char=' ';
    unsigned long k=0, bc_rows=0;

    k = bc_bit_char.to_ulong(); // convert 8 bits to long integer with same bits 
    bc_convert_char = static_cast<unsigned char> (k); // convert long integer to unsigned 

There is a confusion as to which bit is most significant and which is least significant. In the binary constants you provide, the left-most bit is bit 0 which is least significant. In the hex value provided by to_long , the left-most bit is bit 7 which is most significant. If you reverse one or the other then they will be equal.

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