3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * SPDX-License-Identifier: GPL-2.0-or-later
10 #ifndef __WSUTIL_SIGN_EXT_H__
11 #define __WSUTIL_SIGN_EXT_H__
17 #include <wsutil/ws_assert.h>
19 /* sign extension routines */
21 static inline uint32_t
22 ws_sign_ext32(uint32_t val
, int no_of_bits
)
24 ws_assert (no_of_bits
>= 0 && no_of_bits
<= 32);
26 if ((no_of_bits
== 0) || (no_of_bits
== 32))
30 * Don't shift signed values left; that's not valid in C99, at
31 * least, if the value is negative or if the shift count is
32 * the number of bits in the value - 1, and we might get
33 * compile-time or run-time complaints about that.
35 if (val
& (1U << (no_of_bits
-1)))
36 val
|= (0xFFFFFFFFU
<< no_of_bits
);
41 static inline uint64_t
42 ws_sign_ext64(uint64_t val
, int no_of_bits
)
44 ws_assert (no_of_bits
>= 0 && no_of_bits
<= 64);
46 if ((no_of_bits
== 0) || (no_of_bits
== 64))
50 * Don't shift signed values left; that's not valid in C99, at
51 * least, if the value is negative or if the shift count is
52 * the number of bits in the value - 1, and we might get
53 * compile-time or run-time complaints about that.
55 if (val
& (UINT64_C(1) << (no_of_bits
-1)))
56 val
|= (UINT64_C(0xFFFFFFFFFFFFFFFF) << no_of_bits
);
62 static inline uint64_t
63 ws_sign_ext64(uint64_t val, int no_of_bits)
65 int64_t sval = (val << (64 - no_of_bits));
67 return (uint64_t) (sval >> (64 - no_of_bits));
71 #endif /* __WSUTIL_SIGN_EXT_H__ */