libcoap 4.3.5-develop-08ae1a7
Loading...
Searching...
No Matches
coap_encode.c
Go to the documentation of this file.
1/* coap_encode.c -- encoding and decoding of CoAP data types
2 *
3 * Copyright (C) 2010-2025 Olaf Bergmann <bergmann@tzi.org>
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 *
7 * This file is part of the CoAP library libcoap. Please see
8 * README for terms of use.
9 */
10
17
18/* Carsten suggested this when fls() is not available: */
19#ifndef HAVE_FLS
20int
21coap_fls(unsigned int i) {
22 return coap_flsll(i);
23}
24#endif
25
26#ifndef HAVE_FLSLL
27int
28coap_flsll(long long j) {
29 unsigned long long i = (unsigned long long)j;
30 int n;
31 for (n = 0; i; n++)
32 i >>= 1;
33 return n;
34}
35#endif
36
37unsigned int
38coap_decode_var_bytes(const uint8_t *buf, size_t len) {
39 unsigned int i, n = 0;
40 for (i = 0; i < len; ++i)
41 n = (n << 8) + buf[i];
42
43 return n;
44}
45
46unsigned int
47coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val) {
48 unsigned int n, i;
49
50 if (val == 0)
51 return 0;
52
53 for (n = 0, i = val; i && n < sizeof(val); ++n)
54 i >>= 8;
55
56 if (n > length) {
57 assert(n <= length);
58 return 0;
59 }
60 i = n;
61 while (i--) {
62 buf[i] = val & 0xff;
63 val >>= 8;
64 }
65
66 return n;
67}
68
69uint64_t
70coap_decode_var_bytes8(const uint8_t *buf, size_t len) {
71 unsigned int i;
72 uint64_t n = 0;
73 for (i = 0; i < len && i < sizeof(uint64_t); ++i)
74 n = (n << 8) + buf[i];
75
76 return n;
77}
78
79unsigned int
80coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val) {
81 unsigned int n, i;
82 uint64_t tval = val;
83
84 if (val == 0)
85 return 0;
86
87 for (n = 0; tval && n < sizeof(val); ++n)
88 tval >>= 8;
89
90 if (n > length) {
91 assert(n <= length);
92 return 0;
93 }
94 i = n;
95 while (i--) {
96 buf[i] = val & 0xff;
97 val >>= 8;
98 }
99
100 return n;
101}
int coap_flsll(long long j)
Definition coap_encode.c:28
int coap_fls(unsigned int i)
Definition coap_encode.c:21
Library specific build wrapper for coap_internal.h.
unsigned int coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:47
unsigned int coap_decode_var_bytes(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:38
uint64_t coap_decode_var_bytes8(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition coap_encode.c:70
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition coap_encode.c:80