簡體   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