嗯,这是你需要的简单函数:
#include <iostream>
void moveAByte( unsigned long int& destinationLong, const int& sourceInt,
const std::size_t destByteOffset, const std::size_t sourceByteOffset )
{
uint8_t* const firstByteAddressOfLong { reinterpret_cast<uint8_t* const>( &destinationLong ) };
const uint8_t* const firstByteAddressOfInt { reinterpret_cast<const uint8_t* const>( &sourceInt ) };
*( firstByteAddressOfLong + destByteOffset ) = *( firstByteAddressOfInt + sourceByteOffset );
}
int main( )
{
unsigned long int v1 { 0x12'34'56'78 }; // a sample number
int v2 { 0x19'ab'cd'ef }; // another sample number
const std::size_t destByteOffset { 3 }; // Here choose between 0, 1, 2 ,3
const std::size_t sourceByteOffset { 0 }; // the same here
std::cout << '\n';
std::cout << "Before copying the byte " << sourceByteOffset << " of v2 to byte " << destByteOffset << " of v1" << "\n\n"
<< std::showbase << std::hex << "v1 address: " << &v1 << " --> " << "v1 value: " << v1 << '\n'
<< "v2 address: " << &v2 << " --> " << "v2 value: " << v2 << '\n';
std::cout << std::dec << '\n' << "------------------------------------------------------" << "\n\n";
moveAByte( v1, v2, destByteOffset, sourceByteOffset ); // source byte located in v2 is copied to destination byte located in v1
std::cout << "After copying the byte " << sourceByteOffset << " of v2 to byte " << destByteOffset << " of v1" << "\n\n"
<< std::showbase << std::hex << "v1 address: " << &v1 << " --> " << "v1 value: " << v1 << '\n'
<< "v2 address: " << &v2 << " --> " << "v2 value: " << v2 << '\n';
return 0;
}
示例输出:
Before copying the byte 0 of v2 to byte 3 of v1
v1 address: 0x8504fffc78 --> v1 value: 0x12345678
v2 address: 0x8504fffc7c --> v2 value: 0x19abcdef
------------------------------------------------------
After copying the byte 0 of v2 to byte 3 of v1
v1 address: 0x8504fffc78 --> v1 value: 0xef345678
v2 address: 0x8504fffc7c --> v2 value: 0x19abcdef
可以看出,在本例中,v2 的最低有效字节 ef 被复制到v1 的最高有效字节 12 但现在它也是 ef。
使用函数moveAByte,您可以轻松地将v1中的任何字节复制到v2中的任何位置。
注意:此代码仅适用于 little-endian 机器,不适用于 big-endian 个。
注意:在我的平台 (Windows) 上,long 是 4 个字节。在 macOS 和 Linux 上它是 8 个字节。因此,如果您使用的是 macOS 或 Linux,请不要忘记考虑这一点。