[m-rev.] for review: add conversion fucntions from bytes to 16-bit integers
Peter Wang
novalazy at gmail.com
Tue Oct 10 15:05:02 AEDT 2017
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.
> >> @@ -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?
Yes.
Peter
More information about the reviews
mailing list