[m-rev.] for review: add a reverse_bytes/1 function for the 16- and 32-bit types

Julien Fischer jfischer at opturion.com
Mon Sep 25 15:11:37 AEST 2017


Hi Peter,

On Sun, 24 Sep 2017, Peter Wang wrote:

> On Thu, 21 Sep 2017 21:06:26 -0400 (EDT), Julien Fischer <jfischer at opturion.com> wrote:
>>
>> Add a reverse_bytes/1 function for the 16- and 32-bit types.
>>
>> Add functions for reversing the bytes in the int16, int32, uint16 and uint32
>> types.  These are intended for use in implementing endianness conversions.
>>
>> library/int16.m:
>> library/uint16.m:
>> library/int32.m:
>> library/uint32.m:
>>      As above.
>>
>> Julien.
>>
>> diff --git a/library/int16.m b/library/int16.m
>> index 359bbe9..651681d 100644
>> --- a/library/int16.m
>> +++ b/library/int16.m
> ...
>> @@ -388,6 +394,37 @@ max_int16 = 32_767_i16.
>>
>>   %---------------------------------------------------------------------------%
>>
>> +:- pragma foreign_proc("C",
>> +    reverse_bytes(A::in) = (B::out),
>> +    [will_not_call_mercury, promise_pure, thread_safe],
>> +"
>> +#if defined(MR_GNUC) || defined(MR_CLANG)
>> +    B = (int16_t) __builtin_bswap16((uint16_t)A);
>> +#else
>> +    B = ((uint16_t)A >> 8) | (A << 8);
>> +#endif
>> +").
>
> I find this kind of code easier to follow with the masks indicating the
> bits that will be kept, as in the int32 version.

Ok; (the assembly code generate is the same in either case).

> It looks fine, otherwise.

I'll hold off committing this one until it has been merged with the
change for writing 16- and 32-bit integers to binary streams.

Julien.


More information about the reviews mailing list