Re: [PATCH 4/9] drivers/iio: Sign extend without triggering implementation-defined behavior

From: Jonathan Cameron
Date: Wed Oct 30 2019 - 15:44:00 EST


On Mon, 28 Oct 2019 13:06:55 -0700
Bart Van Assche <bvanassche@xxxxxxx> wrote:

> From the C standard: "The result of E1 >> E2 is E1 right-shifted E2 bit
> positions. If E1 has an unsigned type or if E1 has a signed type and a
> nonnegative value, the value of the result is the integral part of the
> quotient of E1 / 2E2 . If E1 has a signed type and a negative value, the
> resulting value is implementation-defined."
>
> Hence use sign_extend_24_to_32() instead of "<< 8 >> 8".

+CC linux-iio

>
> Cc: Jonathan Cameron <jic23@xxxxxxxxxx>
> Cc: Hartmut Knaack <knaack.h@xxxxxx>
> Cc: Lars-Peter Clausen <lars@xxxxxxxxxx>
> Cc: Peter Meerwald-Stadler <pmeerw@xxxxxxxxxx>
> Signed-off-by: Bart Van Assche <bvanassche@xxxxxxx>
> ---
> drivers/iio/common/st_sensors/st_sensors_core.c | 7 +------
> 1 file changed, 1 insertion(+), 6 deletions(-)
>
> diff --git a/drivers/iio/common/st_sensors/st_sensors_core.c b/drivers/iio/common/st_sensors/st_sensors_core.c
> index 4a3064fb6cd9..94a9cec69cd7 100644
> --- a/drivers/iio/common/st_sensors/st_sensors_core.c
> +++ b/drivers/iio/common/st_sensors/st_sensors_core.c
> @@ -21,11 +21,6 @@
>
> #include "st_sensors_core.h"
>
> -static inline u32 st_sensors_get_unaligned_le24(const u8 *p)
> -{
> - return (s32)((p[0] | p[1] << 8 | p[2] << 16) << 8) >> 8;
> -}
> -
> int st_sensors_write_data_with_mask(struct iio_dev *indio_dev,
> u8 reg_addr, u8 mask, u8 data)
> {
> @@ -556,7 +551,7 @@ static int st_sensors_read_axis_data(struct iio_dev *indio_dev,
> else if (byte_for_channel == 2)
> *data = (s16)get_unaligned_le16(outdata);
> else if (byte_for_channel == 3)
> - *data = (s32)st_sensors_get_unaligned_le24(outdata);
> + *data = get_unaligned_signed_le24(outdata);
>
> st_sensors_free_memory:
> kfree(outdata);