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