سؤال

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.

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. (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.

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.

41424344
هل كانت مفيدة؟

المحلول 2

So this is a quick hack, however I was wondering if other platforms support a similar instruction that is similar to BSWAP.

    asm volatile ("movl %1,%%eax;\n"
                  "bswapl %%eax;\n"
                  "movl %%eax, %0;\n"
             : "=r" (Dword)
             : "r" (Dword)
             : "%eax"
             );

نصائح أخرى

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.

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top