In C, I have a variable of the type uint64 ( x ) and a variable of type int ( i ). I need to change the MSB of x to the value of i (which will vary). How can I achieve that. Please help!
int i;
//
.. some code here that will set i to 0 or to 1.
//
uint64_t x = 0xbeefcafebabecab1;
The binary representation of x is: 1011111011101111110010101111111010111010101111101100101010110001. I need to change the MSB (the leftmost 1 in this case) to the current value of i (say one or zero) How can i achieve that? I have some ideas but i'm getting more confused. Any suggestions will be really helpful.
Pretty much like this:
#include <stdio.h>
#include <stdint.h>
int main() {
uint64_t x = 0x0f9c432a673750a1;
for (int i = 0; i < 2; ++i) {
if ( i )
x |= ((uint64_t) 1 << 63);
else
x &= ~((uint64_t) 1 << 63);
printf ("i: %d x: %lx\n", i, x);
}
}
John
As you are interesting only on MSB, it is importante to take care of the endiness. To do so, I've adapted the JohnRowe code for this:
#include <stdio.h>
#include <stdint.h>
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define _MSB_BIT_MASK_UINT64 (63)
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define _MSB_BIT_MASK_UINT64 (0)
#else
#error "Unknown endiness"
#endif
#define _MSB_MASK_UINT64 ((uint64_t) 1 << _MSB_BIT_MASK_UINT64)
#define _SET_MSB_UINT64(x) (x | _MSB_MASK_UINT64)
#define _CLEAR_MSB_UINT64(x) (x & ~_MSB_MASK_UINT64)
void printMessage(int i, uint64_t x)
{
printf ("i: %d x: %llx\n", i, x);
}
int main() {
uint64_t x1 = 0x0123456789ABCDEF;
uint64_t x2 = 0x8FEDCBA987654321;
printMessage(0, _CLEAR_MSB_UINT64(x1));
printMessage(1, _SET_MSB_UINT64(x1));
printMessage(0, _CLEAR_MSB_UINT64(x2));
printMessage(1, _SET_MSB_UINT64(x2));
}
The macro BYTE_ORDER is GCC dependent.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.