Saturday, December 29, 2012

32 bit Integer value vs. 32 bit Hex value

A 32-bit unsigned integer value can be from 0 to 2^32-1.
That is, from 0 to 2147483647. Well, if somebody wants to remember the maximum value of integer they can remember it very easily because its a 10 digit number and so, pretend it as a phone number- assuming you're in the US the value can be remembered as : 214-748-3647 

Similarly,64-bit unsigned integer value can be from 0 to 2^64-1 .

Now, 32-bit hex value can be from 0 to 0x7f f f f f f f
There will be only 8 digits i.e. 7 f f f f f f f  because 1 digit corresponds to 4 bit. Hence 8 digits correspond to 8*4=32 bits.

So, does that mean the digits which are followed by 0x are hexadecimal ... ?
The answer is yes.

Now, if you want to send 32-bit integer value on a network or want to use 32-bit integer value in a program how will you be sure that the value you are sending on a network or using in a program is 32-bit integer ?
It all depends on the programming language.
If you are using statically typed programming languages such as c/c++ ,you can declare the variable using the specific datatype such as follows:
int64_t for declaring variable whose value will be considered as 64-bit.
int32_t for declaring variable whose value will be considered as 32-bit.

If you are using dynamic typed language such as python,you cannot distinguish between 32-bit integer and 64-bit integer in python, hence, you might need some method in order to pack the number  in 32 bit integer value or 64 bit integer value.  For ex. If you are working with python and if you want the number to be in 32 bit integer or if you want to pack the data as [64-bit integer][32-bit integer][32-bit integer] then there is one module named structs which you can use to get the 32-bit integer or to get the packed data as [64-bit data][32-bit data][32-bit data].


import struct

struct.pack('qii', # Format string  here.
            100, # Your 64-bit integer
            50, # Your first 32-bit integer
            25) # Your second 32-bit integer

# This will return the following:
'd\x00\x00\x00\x00\x00\x00\x002\x00\x00\x00\x19\x00\x00\x00'

If you want 32-bit integer then you can write the following program to get the 32-bit integer value.


import struct

struct.pack('i', # Format string  here.
            10) # Your 32-bit integer

# This will return the following:
'\n\x00\x00\x00'


Note the values which are being passed in pack method are integer values. You can also pass hexadecimal values which pack method will convert into 32-bit integer and return it as string. 

No comments:

Post a Comment