Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

Which C datatype can represent a 40-bit binary number?

I need to represent a 40-bit binary number. Which C datatype should be used to handle this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're using a C99 or C11 compliant compiler, then use int_least64_t for maximum compatibility. Or, if you want an unsigned type, uint_least64_t. These are both defined in <stdint.h>

<stdint.h> usually also defines int64_t, but since it's not required by the standard, it may not be defined in every implementation. However:

  • int_least64_t - at least 64 bits, and
  • int_fast64_t - the fastest size in this implementation of at least 64 bits

are both required to be present in C99 and C11 (See § 7.18.1.2-3 in the C99 standard, and § 7.20.1.2-3 in the C11 standard).


Although C99 specifies that long long is at least 64 bits on a particular machine (§ 5.2.4.2.1), the types in <stdint.h> are designed to be explicitly portable.

You can read more about integer sizes on different platforms here. Note that the size of integer types are a problem with the long data type - on 64 bit Windows, it's currently 32 bits, whereas on 64 bit linux it's 64 bits. For this reason, I believe you're safest using the types from <stdint.h>

It's worth noting that some feel that long long is more readable. Personally, I prefer the types from <stdint.h>, because they allow you to say what you mean when you use them - which I find more readable. Of course, readability is often a matter of taste - and if you're working with an existing codebase, I'd just follow whatever they do :)


If your compiler only supports C89, then R..'s solution will allow you up to 53 bits of integer precision.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...