简体   繁体   中英

How to split a 64-bit number into eight 8-bit values?

Is there a simple way to split one 64-bit ( unsigned long long ) variable into eight int8_t values?

For example:

//1001000100011001100100010001100110010001000110011001000110011111
unsigned long long bigNumber = 10455547548911899039;
int8_t parts[8] = splitULongLong(bigNumber);

parts would be something along the lines of:

[0] 10011111

[1] 10010001

[2] 00011001

...

[7] 10010001

You should be able to use a Union to split the data up without any movement or processing.

This leaves you with the problem of the resulting table being in hte wrong order which can be easily solved with a macro (if you have lots of hard coded values) or a simple "8-x" subscript calculation.

#define rv(ss) = 8 - ss;


union SameSpace {
unsigned long long _64bitVariable;
int8_t _8bit[8];
} samespace;

_64bitVariable = 0x1001000100011001100100010001100110010001000110011001000110011111;

if (_8bit[rv(1)] == 0x10011111) {
   printf("\n correct");
}

First you shouldn't play such games with signed values, this only complicates the issue. Then you shouldn't use unsigned long long directly, but the appropriate fixed width type uint64_t . This may be unsigned long long , but not necessarily.

Any byte (assuming 8 bit) in such an integer you may obtain by shifting and masking the value:

#define byteOf(V, I) (((V) >> (I)*8)&UINT64_C(0xFF))

To initialize your array you would place calls to that macro inside an initializer.

BTW there is no standard "binary" format for integers as you seem to be assuming.

我想如果是这样的话:64bit num%8,保存此结果,然后减去结果,然后将结果除以8,最后保存num并保存(64bit num%8)num,最后得到两个8bit num,并且您可以使用这两个num替换64bit num。但是,当您需要操作时,可能需要将8bit num转换为64 bit mun。

 {
   uint64_t v= _64bitVariable;
   uint8_t i=0,parts[8]={0};
   do parts[i++]=v&0xFF; while (v>>=8);
 }

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.

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