Wireshark  4.3.0
The Wireshark network protocol analyzer
sign_ext.h
Go to the documentation of this file.
1 
10 #ifndef __WSUTIL_SIGN_EXT_H__
11 #define __WSUTIL_SIGN_EXT_H__
12 
13 #include <inttypes.h>
14 
15 #include <glib.h>
16 
17 #include <wsutil/ws_assert.h>
18 
19 /* sign extension routines */
20 
21 static inline uint32_t
22 ws_sign_ext32(uint32_t val, int no_of_bits)
23 {
24  ws_assert (no_of_bits >= 0 && no_of_bits <= 32);
25 
26  if ((no_of_bits == 0) || (no_of_bits == 32))
27  return val;
28 
29  /*
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.
34  */
35  if (val & (1U << (no_of_bits-1)))
36  val |= (0xFFFFFFFFU << no_of_bits);
37 
38  return val;
39 }
40 
41 static inline uint64_t
42 ws_sign_ext64(uint64_t val, int no_of_bits)
43 {
44  ws_assert (no_of_bits >= 0 && no_of_bits <= 64);
45 
46  if ((no_of_bits == 0) || (no_of_bits == 64))
47  return val;
48 
49  /*
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.
54  */
55  if (val & (UINT64_C(1) << (no_of_bits-1)))
56  val |= (UINT64_C(0xFFFFFFFFFFFFFFFF) << no_of_bits);
57 
58  return val;
59 }
60 
61 /*
62 static inline uint64_t
63 ws_sign_ext64(uint64_t val, int no_of_bits)
64 {
65  int64_t sval = (val << (64 - no_of_bits));
66 
67  return (uint64_t) (sval >> (64 - no_of_bits));
68 }
69 */
70 
71 #endif /* __WSUTIL_SIGN_EXT_H__ */