例如,考虑下面的c++代码
#include <iostream>
#include <cstdio>
using namespace std;
typedef unsigned long long u64;
typedef unsigned short u16;
void call(u16& c)
{
cout<<"nc: "<<hex<<c;
c=0x2323;
}
int main() {
u64 c1=0x12345678;
call(c1);
cout<<"nc1: "<<hex<<c1;
return 0;
}
编译错误:类型为"u16&类型为"u64{aka long long unsigned int}"的表达式
由于u64
的位数是u16
的四倍,因此使其适合的唯一方法是将其切成四块,一次喂一块,然后在另一侧将它们重新组装在一起,就像分段沙发一样:
u64 c1=0x12345678;
u16 firstPart = (u16)(c1 & 0xFFFF);
call(firstPart);
u16 secondPart = (u16)((c1>>16) & 0xFFFF);
call(secondPart);
u16 thirdPart = (u16)((c1>>32) & 0xFFFF);
call(thirdPart);
u16 fourthPart = (u16)((c1>>48) & 0xFFFF);
call(fourthPart);
c1 = ((u64)firstPart) |
(((u64)secondPart)<<16) |
(((u64)thirdPart)<<32) |
(((u64)forthPart)<<48);
更新:一个更严肃的答案,基于评论中的细节:
void call(u16& c)
{
cout<<"nc: "<<hex<<c;
c=0x2323;
}
// wrapper function to allow passing u64s in.
// The least significant 16 bits of the u64 will be modified by call(u16&)
void call(u64& c)
{
u16 lowBits = (u16)(c&0xFFFF);
call(lowBits);
c &= ~((u64)(0xFFFF));
c |= (u64)lowBits;
}