Setting a buffer of char* with intermediate casting to int*

前端 未结 6 607
一向
一向 2021-01-11 17:23

I could not fully understand the consequences of what I read here: Casting an int pointer to a char ptr and vice versa

In short, would this work?

set         


        
6条回答
  •  佛祖请我去吃肉
    2021-01-11 18:02

    Your code is perfect for working with any architecture with 32bit and up. There is no issue with byte ordering since all your source bytes are 0xFF.

    At x86 or x64 machines, the extra work necessary to deal with eventually unaligned access to RAM are managed by the CPU and transparent to the programmer (since Pentium II), with some performance cost at each access. So, if you are just setting the first four bytes of a buffer a few times, you are good to simplify your function:

    void set4Bytes(unsigned char* buffer) {
      const uint32_t MASK = 0xffffffff;
      *((uint32_t *)buffer) = MASK;
    }
    

    Some readings:

    1. A Linux kernel doc about UNALIGNED MEMORY ACCESSES
    2. Intel Architecture Optimization Manual, section 3.4
    3. Windows Data Alignment on IPF, x86, and x64
    4. A Practical 'Aligned vs. unaligned memory access', by Alexander Sandler

提交回复
热议问题