[m-rev.] for review: add conversion fucntions from bytes to 16-bit integers
Julien Fischer
jfischer at opturion.com
Tue Oct 10 15:29:13 AEDT 2017
Hi Peter,
On Tue, 10 Oct 2017, Peter Wang wrote:
> On Mon, 9 Oct 2017 23:47:34 -0400 (EDT), Julien Fischer <jfischer at opturion.com> wrote:
>>
>> Hi Peter,
>>
>> On Tue, 10 Oct 2017, Peter Wang wrote:
>>
>>>
>>> We also need to specify what happens on overflow.
>>
>> How will overflow occur here?
>
> Maybe overflow is the wrong word. If the MSB has the high bit set then
> the resulting value depends on how negative numbers are encoded.
Technically, you're right.
In the thread about undefined integer behaviour from last year
<http://lists.mercurylang.org/archives/reviews/2016-October/019030.html>
I think we were basically in agreement that Mercury's int type (as it
was then, signed integer types as it is now) should be defined to be
two's complement. (C# and Java require that and GCC doesn't support any
other integer representation anyway,
<https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Integers-implementation.html#Integers-implementation>)
My intention is to revisit everything in the above thread in the nearish
future, part of which would involve nailing down what numeric
representations Mercury uses (i.e. by stating them in the reference
manual).
>>>> @@ -316,6 +328,44 @@ cast_from_uint16(_) = _ :-
>>>>
>>>> %---------------------------------------------------------------------------%
>>>>
>>>> +:- pragma foreign_proc("C",
>>>> + from_bytes_le(LSB::in, MSB::in) = (I16::out),
>>>> + [will_not_call_mercury, promise_pure, thread_safe, will_not_modify_trail],
>>>> +"
>>>> + unsigned char *int16_bytes = (unsigned char *) &I16;
>>>> +#if defined(MR_BIG_ENDIAN)
>>>> + int16_bytes[0] = MSB;
>>>> + int16_bytes[1] = LSB;
>>>> +#else
>>>> + int16_bytes[0] = LSB;
>>>> + int16_bytes[1] = MSB;
>>>> +#endif
>>>> +").
>>>
>>> Is this to avoid undefined behaviour if shifting overflows?
>>
>> Do you mean why do it this way rather than using the shift-and-or
>> approach that C# and Java use?
The above results in less instructions being generated.
Julien.
More information about the reviews
mailing list