Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain the significance of using uint32_t from the library <stdint.h>?

Tags:

c++

I recently saw someones code that was using this variable type and library on code chef. I was wondering if someone can explain the benefits of using uint32_t as opposed to int, float, double, etc. Also what cases should I use/not use it?

Link to code: http://www.codechef.com/viewsolution/131898

like image 598
user3754017 Avatar asked Sep 29 '22 22:09

user3754017


1 Answers

The advantage is that a uint32_t is always guaranteed to be 32 bits long, as opposed to the primitive types whose lengths are platform-dependent. For instance, while ints are 32 bits on x86 and x86_64, they are 64 bits on many other 64-bit platforms, and less than that on some older and/or embedded architectures.

One of the cases where it may be beneficial to use a uint32_t, then, could be when you read binary data directly to/from disk/network. You can always just copy 4 bytes into a uint32_t and be sure that it fits. (You'd still have to watch out for eg. differences in endianness, however.)

You may also want to use a uint32_t if you simply want predictable overflow/underflow behavior. Or if you're doing calculations defined in some specific size, like when running some hashing algorithms.

The only thing I have been left wondering is why there aren't corresponding float32_t and float64_t types. :)

like image 129
Dolda2000 Avatar answered Oct 08 '22 21:10

Dolda2000