libcoap 4.3.1
encode.c
Go to the documentation of this file.
1/* encode.c -- encoding and decoding of CoAP data types
2 *
3 * Copyright (C) 2010,2011 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
16#include "coap3/coap_internal.h"
17
18/* Carsten suggested this when fls() is not available: */
19#ifndef HAVE_FLS
20int coap_fls(unsigned int i) {
21 return coap_flsll(i);
22}
23#endif
24
25#ifndef HAVE_FLSLL
26int coap_flsll(long long i)
27{
28 int n;
29 for (n = 0; i; n++)
30 i >>= 1;
31 return n;
32}
33#endif
34
35unsigned int
36coap_decode_var_bytes(const uint8_t *buf, size_t len) {
37 unsigned int i, n = 0;
38 for (i = 0; i < len; ++i)
39 n = (n << 8) + buf[i];
40
41 return n;
42}
43
44unsigned int
45coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val) {
46 unsigned int n, i;
47
48 for (n = 0, i = val; i && n < sizeof(val); ++n)
49 i >>= 8;
50
51 if (n > length) {
52 assert (n <= length);
53 return 0;
54 }
55 i = n;
56 while (i--) {
57 buf[i] = val & 0xff;
58 val >>= 8;
59 }
60
61 return n;
62}
63
64uint64_t
65coap_decode_var_bytes8(const uint8_t *buf, size_t len) {
66 unsigned int i;
67 uint64_t n = 0;
68 for (i = 0; i < len; ++i)
69 n = (n << 8) + buf[i];
70
71 return n;
72}
73
74unsigned int
75coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val) {
76 unsigned int n, i;
77 uint64_t tval = val;
78
79 for (n = 0; tval && n < sizeof(val); ++n)
80 tval >>= 8;
81
82 if (n > length) {
83 assert (n <= length);
84 return 0;
85 }
86 i = n;
87 while (i--) {
88 buf[i] = val & 0xff;
89 val >>= 8;
90 }
91
92 return n;
93}
Pulls together all the internal only header files.
int coap_flsll(long long i)
Definition: encode.c:26
int coap_fls(unsigned int i)
Definition: encode.c:20
unsigned int coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val)
Encodes multiple-length byte sequences.
Definition: encode.c:45
unsigned int coap_decode_var_bytes(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition: encode.c:36
uint64_t coap_decode_var_bytes8(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition: encode.c:65
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition: encode.c:75