[英]Copying 4 bytes directly into a DWORD (MSB becomes LSB)
So I was looking at the assembly instructions for memcpy
and I was wondering if an assembly instruction embedded within the code was responsible for the (Most Significant Byte being altered into the Least Significant Byte) after the memcpy
being executed. 因此,我正在查看
memcpy
的汇编指令,并且想知道嵌入在代码中的汇编指令是否负责执行memcpy
之后的(最高有效字节被更改为最低有效字节)。
http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/osfmk/x86_64/bcopy.s http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/osfmk/x86_64/bcopy.s
ENTRY(memcpy)
movq %rdx,%rcx
shrq $3,%rcx /* copy by 64-bit words */
cld // is this instruction responsible for the MSB being switched to LSB
rep
movsq
movq %rdx,%rcx
andq $7,%rcx /* any bytes left? */
rep
movsb
ret
I want memcpy
to copy Octet[0]
into the the DWORD
variable while preserving it as the Most Significant Byte. 我希望
memcpy
将Octet[0]
复制到DWORD
变量中,同时将其保留为最高有效字节。 (31-23) (31-23)
#include <iostream>
using namespace std;
int main()
{
unsigned char Octet[4];
Octet[0] = 'A';
Octet[1] = 'B';
Octet[2] = 'C';
Octet[3] = 'D';
unsigned int Dword;
memcpy( &Dword, Octet, 4);
cout << hex << Dword << endl;
So after calling memcpy the values are stored into the DWORD
in the following order. 因此,在调用memcpy之后,值将按以下顺序存储到
DWORD
中。
44434241
If I created a custom memcpy function while removing the CLD
instruction would preserve the byte order or replacing it with SLD
would be a viable solution to get the desired result. 如果我在删除
CLD
指令时创建了一个自定义的memcpy函数,将保留字节顺序或将其替换为SLD
将是获得所需结果的可行解决方案。
41424344
I haven't looked at the actual assembly code, but on any little endian computer you will get the result you have mentioned. 我没有看过实际的汇编代码,但是在任何小型字节序计算机上,您都会得到您提到的结果。 The hex output is always going to print from MSB to LSB and on a little endian computer the MSB will be the last byte.
十六进制输出将始终从MSB打印到LSB,在小端计算机上,MSB将是最后一个字节。
What it sounds like you want would be best accomplished by: 听起来最好的方法是:
Dword = Octet[0] << 24 | Octet[1] << 16 | Octet[2] << 8 | Octet[3];
That's the only standard way I am aware of to put Octet[0] in the MSB down to Octet[3] in the LSB. 这是我知道的将MSB中的Octet [0]降到LSB中的Octet [3]的唯一标准方法。
So this is a quick hack, however I was wondering if other platforms support a similar instruction that is similar to BSWAP
. 因此,这是一个快速的技巧,但是我想知道其他平台是否支持类似于
BSWAP
的类似指令。
asm volatile ("movl %1,%%eax;\n"
"bswapl %%eax;\n"
"movl %%eax, %0;\n"
: "=r" (Dword)
: "r" (Dword)
: "%eax"
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.