Using which macro, MSB of a no. can be set??
Using which macro, MSB of a no. can be set??
if you consider a 32 bit int you can use
Code:int i = 0; i = ( i | ( 1 << 32 ) ); // Set MSB
Of course, doing this without assuming a specific number of bits in the number is more interesting.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Shouldn't it be?Code:#define SETMSB(x) (x) |= 1 << (sizeof(x) * CHAR_BITS))My guess is that all this would only work for datatypes that can fit into processor registers.Code:#define SETMSB(x) (x) |= 1 << ((sizeof(x) * CHAR_BITS) - 1))
Last edited by pankaj401; 01-10-2008 at 05:19 AM.
Of course it should - I pointed out your mistake, then made the same one myself.
It would work for any type that the compiler is capable of producing a correct shift left operation for, so for example a _int64 type on MS Visual Studio, or "long long" in gcc, both work on 32-bit targets. The code produced will perform the correct multiinstruction shift, using for the x86 instruction SHLD for example. It is entirely possible to produce code on machines that doesn't have a specific SHLD instruction too - by using rotate with carry for example.
Although I guess if you use "long long", the 1 would need to be postfixed by "LL" to make sure that the compiler doesn't say to itself "1 is an 32-bit integer, shift that more than 31 bits and it turns into zero, so let's remove all the code here". This can be fixed, either by multiple macros [for different types], or by passing the type of the data in and using that to cast the 1 to the correct type.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.