Thinking and talking about the issue of whether my OS is 32-bit or a 64-bit one, I found out there were many ways to know that. But we discuss none of them over here. Here we discuss a cool way in order to find it out.
We all know about pointers in C right? It points to a memory location. That is it holds an address whose contents maybe dereferenced using the ‘*’ operator. There I already said it! The pointer stores an address.
But what is the size of an address? And who determines it?
That is where the matter of 32 and 64 bit comes in. A 32-bit OS means that its addresses are of size 32-bits and it can address upto 2^32 memory locations. As such, a maximum of 4GB. In a previous post of mine, I have mentioned the fact of the file system FAT32 not supporting files larger than 4GB. It is because that file system uses 32-bit addressing.
But our concern is with the OS. The OS determines the addressing and as such, a 32-bit OS allocates 32 bits to a pointer whereas a 64-bit OS allocates 64 bits to a pointer.
We can exploit this allocation to find out if the OS running on our system is 32 or 64 bit. For that, we write a small C code as follows:
#include<stdio.h>
int main(){
int *p;
printf(“Size is : %d\n”, sizeof(p));
return 0;
}
Compile the code using gcc as:
gcc filename.c
And run it as:
./a.out
See what number you get as your output. If it is 4, your OS is 32-bit and if it 8, your OS is 64-bit. This is because the 4 and 8 are shown in bytes.
I was hoping to get a way of knowing what my system’s architecture is. But this method can only recognize the OS and not the system.
Happy hacking!
That’s a cool hack ! We should find a way to know system ‘s architecture using C 🙂
C is a beauty. And yeah, we have to figure out some way of knowing it. 🙂
This helps us to check whether the CPU is 32bit of 64bit using /proc/cpuinfo – http://www.cyberciti.biz/faq/linux-how-to-find-if-processor-is-64-bit-or-not/
Cool.
grep flags /proc/cpuinfo does do the trick. I tried it on a 64-bit system that is running a 32-bit OS and there was “lm” in every line of the out put.
However getconf LONG_BIT is only suitable to identify if the OS is 32 bit or not and has got nothing to do with the system’s architecture..
Thanks for the site Ershad! 🙂
cat /proc/cpuinfo
waaaay easier
scratch that…my bad…
I just wish that you would get your facts straight before you shout out. 😉
You should use the format specifier %zu to print the size, since sizeof returns a size_t, which will not be an int (%d) on 64b machines.