Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

write_signed cannot handle 32 bits #3

Open
kawogi opened this issue Jan 25, 2019 · 2 comments
Open

write_signed cannot handle 32 bits #3

kawogi opened this issue Jan 25, 2019 · 2 comments

Comments

@kawogi
Copy link

kawogi commented Jan 25, 2019

Running the code

BitWriter::endian(Vec::new(), LittleEndian).write_signed(32, 0).unwrap();

results in the following error message
excessive value for bits written
(same for BigEndian and all other values)

@Ashymad
Copy link

Ashymad commented Mar 16, 2020

Yup, I've run into this issue as well. It generally happens when you try to write_signed() a value with the exact number of bits as the bit number parameter. In the example above you try to write 32 bits of a 0 (which defaults to 0i32 in Rust). The problem is caused by this assertion:

bitstream-io/src/write.rs

Lines 215 to 219 in 29973ff

} else if (bits < U::bits_size()) && (value >= (U::one() << bits)) {
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"excessive value for bits written",
))

The write_signed() function calls write() on value with sign bit removed and bits - 1 as the bits parameter, however as the type is signed the operation U::one() << bits moves 1 into the sign bit resulting in the minimum signed int value for the type. As every possible input value is greater than the minimum type value the error is raised.

For example let's try to write_signed(8, 0i8). 0i8 is 0b00000000 in binary. The sing bit 0 is pushed into the queue and write(7, 0i8) is called. Computing 1i8 << 7 == 0b00000001 << 7 results in 0b10000000 == -128i8. 0 is greater than -128 so the error is raised.

@sdroege
Copy link
Contributor

sdroege commented Oct 31, 2023

This was fixed in 5c5dd5a it seems

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants