繁体   English   中英

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

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

在C语言中,我有一个uint64( x )类型的变量和一个int( i )类型的变量。 我需要将x的MSB更改为i的值(这将有所不同)。 我该如何实现。 请帮忙!

int i;
//
.. some code here that will set i to 0 or to 1. 
//

uint64_t x = 0xbeefcafebabecab1;

x的二进制表示形式为:1011111011101111110010101111111010111010101111101100101010110001.我需要将MSB(在这种情况下,最左边的1)更改为i的当前值(比如说一个或零),我该如何实现? 我有一些想法,但我变得更加困惑。 任何建议都会非常有帮助。

几乎是这样的:

#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);
    }

}

约翰

由于您仅对MSB感兴趣,因此重要的是要注意其持久性。 为此,我为此修改了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));
}

BYTE_ORDER与GCC有关。

暂无
暂无

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

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