简体   繁体   English

在C语言中,如何根据变量设置uint64_t的MSB

[英]In C, how to set the MSB of an uint64_t according to a variable

In C, I have a variable of the type uint64 ( x ) and a variable of type int ( i ). 在C语言中,我有一个uint64( x )类型的变量和一个int( i )类型的变量。 I need to change the MSB of x to the value of i (which will vary). 我需要将x的MSB更改为i的值(这将有所不同)。 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? x的二进制表示形式为:1011111011101111110010101111111010111010101111101100101010110001.我需要将MSB(在这种情况下,最左边的1)更改为i的当前值(比如说一个或零),我该如何实现? 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. 由于您仅对MSB感兴趣,因此重要的是要注意其持久性。 To do so, I've adapted the JohnRowe code for this: 为此,我为此修改了JohnRowe代码:

#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. BYTE_ORDER与GCC有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM