4 * Wireshark - Network traffic analyzer
5 * By Gerald Combs <gerald@wireshark.org>
6 * Copyright 1998 Gerald Combs
8 * SPDX-License-Identifier: GPL-2.0+
11 #ifndef __WSUTIL_SIGN_EXT_H__
12 #define __WSUTIL_SIGN_EXT_H__
16 /* sign extension routines */
19 ws_sign_ext32(guint32 val, int no_of_bits)
21 g_assert (no_of_bits >= 0 && no_of_bits <= 32);
23 if ((no_of_bits == 0) || (no_of_bits == 32))
27 * Don't shift signed values left; that's not valid in C99, at
28 * least, if the value is negative or if the shift count is
29 * the number of bits in the value - 1, and we might get
30 * compile-time or run-time complaints about that.
32 if (val & (1U << (no_of_bits-1)))
33 val |= (0xFFFFFFFFU << no_of_bits);
39 ws_sign_ext64(guint64 val, int no_of_bits)
41 g_assert (no_of_bits >= 0 && no_of_bits <= 64);
43 if ((no_of_bits == 0) || (no_of_bits == 64))
47 * Don't shift signed values left; that's not valid in C99, at
48 * least, if the value is negative or if the shift count is
49 * the number of bits in the value - 1, and we might get
50 * compile-time or run-time complaints about that.
52 if (val & (G_GUINT64_CONSTANT(1) << (no_of_bits-1)))
53 val |= (G_GUINT64_CONSTANT(0xFFFFFFFFFFFFFFFF) << no_of_bits);
60 ws_sign_ext64(guint64 val, int no_of_bits)
62 gint64 sval = (val << (64 - no_of_bits));
64 return (guint64) (sval >> (64 - no_of_bits));
68 #endif /* __WSUTIL_SIGN_EXT_H__ */