blob: 0e1cf1066461afb8a5b2da56c2507830efc176d0 [file] [log] [blame]
kasunath0aa36d82022-11-23 14:24:15 -08001#include "bej_common.h"
kasunath7ffd30a2022-05-10 18:11:34 -07002
kasunath0aa36d82022-11-23 14:24:15 -08003uint64_t bejGetUnsignedInteger(const uint8_t* bytes, uint8_t numOfBytes)
kasunath7ffd30a2022-05-10 18:11:34 -07004{
5 uint64_t num = 0;
6 for (uint8_t i = 0; i < numOfBytes; ++i)
7 {
8 num |= (uint64_t)(*(bytes + i)) << (i * 8);
9 }
10 return num;
11}
12
kasunath0aa36d82022-11-23 14:24:15 -080013uint64_t bejGetNnint(const uint8_t* nnint)
kasunath7ffd30a2022-05-10 18:11:34 -070014{
15 // In nnint, first byte indicate how many bytes are there. Remaining bytes
16 // represent the value in little-endian format.
17 const uint8_t size = *nnint;
kasunath0aa36d82022-11-23 14:24:15 -080018 return bejGetUnsignedInteger(nnint + sizeof(uint8_t), size);
kasunath7ffd30a2022-05-10 18:11:34 -070019}
20
kasunath0aa36d82022-11-23 14:24:15 -080021uint8_t bejGetNnintSize(const uint8_t* nnint)
kasunath7ffd30a2022-05-10 18:11:34 -070022{
23 // In nnint, first byte indicate how many bytes are there.
24 return *nnint + sizeof(uint8_t);
25}
kasunath99bd6c92023-07-30 18:19:00 -070026
27uint8_t bejNnintEncodingSizeOfUInt(uint64_t val)
28{
29 uint8_t bytes = 0;
30 do
31 {
32 // Even if the value is 0, we need a byte for that.
33 ++bytes;
34 val = val >> 8;
35 } while (val != 0);
36 // Need 1 byte to add the nnint length.
37 return bytes + 1;
38}
39
40uint8_t bejNnintLengthFieldOfUInt(uint64_t val)
41{
42 // From the size of the encoded value, we need 1 byte for the length field.
43 return bejNnintEncodingSizeOfUInt(val) - 1;
44}