-1

I'm trying to determine, whether the OS is 32bit or 64bit without using predefined functions or system call. I have created following program.

#include <stdio.h>
int main() 
{
    int i = 1;
    int c = 0;
    while(i) 
    { 
        i = i << 1; 
        c++; 
    } 
    printf("%d\n", c); 

    if (c == 32) 
        printf("OS is 32bit\n");
    else if (c == 64) 
        printf("OS is 64bit\n"); 
    else printf("wrong answer\n"); 
} 

In 32bit os gives corret output, but in 64bit os also print "OS is 32bit". So, I found the reason behind that, In 32bit and 64bit OS natarally size of int 4bytes. So, Is there any way to determine whether the OS is 32bit or 64bit without using predefined functions or system calls?

msc
  • 33,420
  • 29
  • 119
  • 214
  • @Ed Heal i know sir, but is there any way to determine? – msc Mar 18 '17 at 07:47
  • 2
    You will need to make some operating system call to find out anything about the operating system. For Windows, [see here](http://stackoverflow.com/questions/7011071/detect-32-bit-or-64-bit-of-windows) – M.M Mar 18 '17 at 07:47
  • Is it posible to determine without predefine function or system call? – msc Mar 18 '17 at 07:49
  • 2
    No .............. – M.M Mar 18 '17 at 07:51
  • 2
    you might try checking the size of a pointer... http://stackoverflow.com/questions/3853312/sizeof-void-pointer – Erich Kitzmueller Mar 18 '17 at 08:06
  • 2
    If you build 32-bit code on a 64-bit OS, it runs in a 32-bit environment - there is probably no platform independent means of determining the OS type. If you build 64-bit code and it runs it is implicitly a 64 bit platform - the compiler knows what it is building - it is not a run-time issue perhaps. – Clifford Mar 18 '17 at 08:26

2 Answers2

2

Unfortunately the answer is "No". What your code does is determine what size an int variable is defined to be when using the C compiler. A 32 bit integer in C has nothing to do with whether the operating itself is 32 bit or 64 bit. (My OS is 64 bit but running your code states incorrectly "OS is 32bit".) To determine the OS word size you will need access to the operating system definitions and that will require a system call.

Jeffrey Ross
  • 141
  • 3
1
while(i) 
{ 
    i = i << 1; 
    c++; 
} 

Left shift beyond the sign bit has undefined behaviour (your loop doesn't stop magically at n bits).

You can include <stdint.h> and check INTPTR_MAX:

#include <stdio.h>
#include <stdint.h>

#if INTPTR_MAX == INT64_MAX
    #define ARCH 64
#elif INTPTR_MAX == INT32_MAX
    #define ARCH 32
#else
    #define ARCH 0
#endif

int main(void) 
{
    printf("OS is %dbit\n", ARCH);
    return 0;
} 

Or you can can compile for a specific target passing a flag:

gcc -DARCH=32 -o demo demo.c 

/D if you are under Visual Studio.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94