Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

247
Visualizações
memcpy performance vs byte shift

There are 2 variables:

uint32_t var32 = 0xAABBCCDD;
uint8_t var8[4] = { 0, 0, 0, 0 };

Which copying way of var32 to var8 would be faster?

for (size_t i = 0; i < sizeof(uint32_t); i++)
    var8[i] = (uint8_t)(var32 >> (i * 8));

or

memcpy(var8, &var32, sizeof(uint32_t));

I would appreciate all hints.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Assuming a 32bit architecture, the memcpy comes down to a single mov (or similar) instruction. So it is faster. But it's also wrong. From a C point of view, you're invoking implementation defined behaviour doing that. What could happen in reality is that your bytes are ordered wrongly, depending on whether you are on a big endian or little endian platform. So, just use the bit shifting solution instead of worrying about performance.

over 4 years ago · Santiago Trujillo Relatório

0

The memcpy in C is generally guaranteed in modern compilers to optimise to being the fastest way of copying available. However this does assume that it is properly inlined in your implementation.

I also do not believe this causes strict aliasing violations as the two pointers never alias the same memory.

However the order of which the bytes of the int is copied into which byte of the array is implementation defined. If you wished to ensure this would instead always be in the big endian order you could first run htonl on the int which would make it big endian, then the results of the copy would be well defined. This would also optimise to nothing in the case it wasnt needed, making it always the fastest implementation on any system.

If on the other hand you want little endian byte ordering use the htole32 to ensure the int becomes little endian on any hardware. However beware that htole32 is an extension in BSD, Linux and various other OSes and isnt guaranteed to be available on all implementations (read, non standard).

over 4 years ago · Santiago Trujillo Relatório

0

I think memcpy will faster, because it dose not compute only use move. byte shift have tow step compute.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda