On Tue, Apr 16, 2024 at 4:01 PM HAGIO KAZUHITO(萩尾 一仁) <k-hagio-ab@nec.com> wrote:
On 2024/04/16 15:49, Yulong Tang wrote:
>> On Mon, Apr 15, 2024 at 2:32 PM HAGIO KAZUHITO(萩尾 一仁) <k-hagio-ab(a)nec.com&gt;
>> wrote:
>>
>>
>> Sure. The macro '#if __BYTE_ORDER == __BIG_ENDIAN' takes effect on a
>> big-endian machine. But it requires to include the header file 'byteswap.h'
>> as below:
>> #include <byteswap.h>
>>
>> In addition, there is a similar implementation, but I haven't tested it
>> with Yulong's case. Can you help to check if this can work well for you?
>> Yulong.
>>
>> static inline uint16_t
>> get_unaligned_le16 (const uint8_t *p)
>> {
>>    return p[0] | p[1] << 8;
>> }

Ah nice, this looks simple and better.  If it works well on a big-endian
machine too, let's go with this.

I tested these two functions with a test case, for example:

unsigned int x = 0x76543210;

big-endian machine:
call get_unaligned_le16_v1(): 0x5476
call get_unaligned_le16_v2(): 0x5476

little-endian machine:
call get_unaligned_le16_v1(): 0x3210
call get_unaligned_le16_v2(): 0x3210

---------------------------code---------------------------------------
static uint16_t get_unaligned_le16_v1(const void *p) {
uint16_t value;
memcpy(&value, p, sizeof(uint16_t));
   #if __BYTE_ORDER == __BIG_ENDIAN
       return bswap_16(value);
   #else
       return value;
   #endif
}

static inline uint16_t
get_unaligned_le16_v2(const uint8_t *p)
{
  return p[0] | p[1] << 8;
}
---------------------------code---------------------------------------

They have the same results on the little-endian/big-endian machine from my side.


>>
>
> Hi, Lianbo
>
> It works well in my case(little-endian). This looks promising, but I don't have a big-

Thank you for the confirmation, Yulong.
 
Thanks
Lianbo

endian machine to test it on.

Thank you for testing, Yulong.

Thanks,
Kazu