Sign in to follow this  
SymLinked

Any simple method to calculate range from bits?

Recommended Posts

Say I want to send a number across the network. Is there a formula to calculate the range of a number based on how many bits it can represent? I googled but it's difficult to get a good search term going when I don't know what it's called. I tried a few different calculations on my own but that didn't work. Like: bits * 8 = range bits ^ bits = range I'm a mathematical disaster so please guide me. :)

Share this post


Link to post
Share on other sites
Quote:
Original post by SymLinked
Say I want to send a number across the network. Is there a formula to calculate the range of a number based on how many bits it can represent?

I googled but it's difficult to get a good search term going when I don't know what it's called. I tried a few different calculations on my own but that didn't work. Like:

bits * 8 = range
bits ^ bits = range

I'm a mathematical disaster so please guide me. :)
I think you need to explain what you are trying to do.
If you want to know the range of certain data types then you use std::numeric_limits in <climits>.
If you're thinking about compression then you really should give more details because I can tell that you're going to run into a lot of problems.

Share this post


Link to post
Share on other sites
Don't send a fixed size, this uses up memory in most cases. Instead, you can circumvent endianness problems and reduce size by using extended integers.

The idea is that your data is packed as:

(Element 0)
[1bit: sign]
[1bit: continue]
[6bit: base value (0-63)]
(Element n)
[1bit: continue]
[7bit: value (0-127)]

Where the continue bit is set to 1 if there is an (n+1)th element in the sequence. When reading, you multiply the value in element n by 64 + 128 * (n-1) before adding it to the full. When writing, you extract the sign, add one and take the abs if it's negative, divide by 64, and then divide by 128 until you reach zero.

Representable ranges (automatically compressed)

1 byte -64 to 63
2 bytes -8192 to 8191
3 bytes -1048576 to 1048575 (1e6)
4 bytes -134217728 to 134217727 (1e8)


Of course, if your value was designed to fit into a certain integer size (say, 16-bit port number) you should serialize it as "a[0] + a[1] << 8" instead.

Quote:
Original post by iMalc
If you want to know the range of certain data types then you use std::numeric_limits in <climits>.


I'm pretty sure that you won't find a template in a C header [smile] it's actually in <limits>.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this