Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard way to detect bit width of hardware?

Variables of type int are allegedly "one machine-type word in length" but in embedded systems, C compilers for 8 bit micro use to have int of 16 bits!, (8 bits for unsigned char) then for more bits, int behave normally: in 16 bit micros int is 16 bits too, and in 32 bit micros int is 32 bits, etc..

So, is there a standar way to test it, something as BITSIZEOF( int ) ?

like "sizeof" is for bytes but for bits.

this was my first idea

    register c=1;                
    int bitwidth=0;
    do
    {

        bitwidth++;

    }while(c<<=1);

    printf("Register bit width is : %d",bitwidth);

But it takes c as int, and it's common in 8 bit compilers to use int as 16 bit, so it gives me 16 as result, It seems there is no standar for use "int" as "register width", (or it's not respected)

Why I want to detect it? suppose I need many variables that need less than 256 values, so they can be 8, 16, 32 bits, but using the right size (same as memory and registers) will speed up things and save memory, and if this can't be decided in code, I have to re-write the function for every architecture

EDIT After read the answers I found this good article

http://embeddedgurus.com/stack-overflow/category/efficient-cc/page/4/

I will quote the conclusion (added bold)

Thus the bottom line is this. If you want to start writing efficient, portable embedded code, the first step you should take is start using the C99 data types ‘least’ and ‘fast’. If your compiler isn’t C99 compliant then complain until it is – or change vendors. If you make this change I think you’ll be pleasantly surprised at the improvements in code size and speed that you’ll achieve.

like image 876
Hernán Eche Avatar asked Jul 27 '10 17:07

Hernán Eche


People also ask

What is bit width of CPU?

In computer architecture, 64-bit integers, memory addresses, or other data units are those that are 64 bits wide. Also, 64-bit CPUs and ALUs are those that are based on processor registers, address buses, or data buses of that size.

How do I get the size of a word in C++?

The C++ String class has length() and size() function. These can be used to get the length of a string type object. To get the length of the traditional C like strings, we can use the strlen() function. That is present under the cstring header file.


1 Answers

I have to re-write the function for every architecture

No you don't. Use C99's stdint.h, which has types like uint_fast8_t, which will be a type capable of holding 256 values, and quickly.

Then, no matter the platform, the types will change accordingly and you don't change anything in your code. If your platform has no set of these defined, you can add your own.

Far better than rewriting every function.

like image 157
GManNickG Avatar answered Oct 18 '22 23:10

GManNickG