Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda