简体   繁体   中英

boost::dynamic_bitset<> strange behaviour

i'm trying to encode longitude/latitude with 22 bits and a radius with 20 bits but there is something strange with the radius - see an output below, please...

#include <iostream>
#include <cassert>
#include <boost/dynamic_bitset/dynamic_bitset.hpp>
using namespace std;
 
boost::dynamic_bitset<> f2b(int n, float f) {
    assert(sizeof(float) == sizeof(int));
    union {
        float input;
        int output;
    } data;
 
    data.input = f;
    boost::dynamic_bitset<> bits(n, data.output);
                                                                                                               
    return bits;
}
 
int main() {
    // latitude
    cout << f2b(22, (-89.9 + 90) / 180) << '\n';
    // longitude
    cout << f2b(22, (-179.9 + 180) / 360) << '\n';
    // radius
    cout << f2b(20, 10.0) << '\n'; // why this returns '00000000000000000000' ?
 
    return 0;
}

$ ./bits 
0100011010001010110100
0100011010001010110100
00000000000000000000

i'd expect a binary representation of 10 which is 00000000000000001010.

I used this tool to calculate the true bit representation of 10.0f, it's 01000001001000000000000000000000 .

What your code does it return the bottom 20 bits of that which is the 00000000000000000000 that you see.

Now I'd like to explain how to fix your code, but I'm not really sure exactly what you are trying to do. If you can explain I'll do my best to suggest the right way to do it.

[SOLVED] never follow customer's specification w/o thinking - it is not possible to encode all float numbers with 20/22 bits (for example 10.0 dec). thanks @john.

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