Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use leading_zeros/trailing_zeros in platform independent way?

Tags:

rust

I want find the first non-zero bit in the binary representation of a u32. leading_zeros/trailing_zeros looks like what I want:

let x: u32 = 0b01000;
println!("{}", x.trailing_zeros());

This prints 3 as expected and described in the docs. What will happen on big-endian machines, will it be 3 or some other number?

The documentation says

Returns the number of trailing zeros in the binary representation

is it related to machine binary representation (so the result of trailing_zeros depends on architecture) or base-2 numeral system (so result will be always 3)?

like image 796
user1244932 Avatar asked Oct 21 '25 06:10

user1244932


1 Answers

The type u32 respresents binary numbers with 32 bits as an abstract concept. You can imagine them as abstract, mathematical numbers in the range from 0 to 232-1. The binary representation of these numbers is written in the usual convention of starting with the most significant bit (MSB) and ending with the least significant bit (LSB), and the trailing_zeros() method returns the number of trailing zeros in that representation.

Endianness only comes into play when serializing such an integer to bytes, e.g. for writing it to a bytes buffer, a file or the network. You are not doing any of this in your code, so it doesn't matter here.

As mentioned above, writing a number starting with the MSB is also just a convention, but this convention is pretty much universal today for numbers written in positional notation. For programming, this convention is only relevant when formatting a number for display, parsing a number from a string, and maybe for naming methods like trailing_zeros(). When storing an u32 in a register, the bits don't have any defined order.

like image 109
Sven Marnach Avatar answered Oct 24 '25 23:10

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!