sys: util: add a sign_extend and sign_extend_64 functions
Add a sign_extend and sign_extend_64 functions, same as the Linux sign_extend32 and sign_extend64 one. This is useful for sign extending values smaller than 32 bits. Signed-off-by: Fabio Baltieri <fabiobaltieri@google.com>
This commit is contained in:
parent
cbad8eff46
commit
5bb9b129de
|
@ -24,6 +24,7 @@
|
|||
|
||||
#ifndef _ASMLANGUAGE
|
||||
|
||||
#include <zephyr/sys/__assert.h>
|
||||
#include <zephyr/types.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
@ -567,6 +568,36 @@ 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(uint32_t value, uint8_t index)
|
||||
{
|
||||
__ASSERT_NO_MSG(index <= 31);
|
||||
|
||||
uint8_t shift = 31 - index;
|
||||
|
||||
return (int32_t)(value << shift) >> shift;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sign extend a 64 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 63)
|
||||
*/
|
||||
static inline int64_t sign_extend_64(uint64_t value, uint8_t index)
|
||||
{
|
||||
__ASSERT_NO_MSG(index <= 63);
|
||||
|
||||
uint8_t shift = 63 - index;
|
||||
|
||||
return (int64_t)(value << shift) >> shift;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Properly truncate a NULL-terminated UTF-8 string
|
||||
*
|
||||
|
|
Loading…
Reference in a new issue