Skip to content

Commit

Permalink
sys: util: add a sign_extend function
Browse files Browse the repository at this point in the history
Add a sign_extend function, same as the Linux sign_extend32 one. This is
useful for sign extending values smaller than 32 bits.

Signed-off-by: Fabio Baltieri <fabiobaltieri@google.com>
  • Loading branch information
fabiobaltieri committed Feb 10, 2024
1 parent e81acaf commit 9faa7e1
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions include/zephyr/sys/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,19 @@ static inline uint8_t bin2bcd(uint8_t bin)
*/
uint8_t u8_to_dec(char *buf, uint8_t buflen, uint8_t value);

/**
* @brief Sign extend an 8, 16 or 32 bit value using the index bit as sign bit.
*
* @param value The value to sign expand.
* @param index 0 based bit index to sign bit (0 to 31)
*/
static inline int32_t sign_extend(int32_t value, int index)
{
uint8_t shift = 31 - index;

return (int32_t)(value << shift) >> shift;
}

/**
* @brief Properly truncate a NULL-terminated UTF-8 string
*
Expand Down

0 comments on commit 9faa7e1

Please sign in to comment.