libcoap 4.3.4
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,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
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 for (n = 0, i = val; i && n < sizeof(val); ++n)
51 i >>= 8;
52
53 if (n > length) {
54 assert(n <= length);
55 return 0;
56 }
57 i = n;
58 while (i--) {
59 buf[i] = val & 0xff;
60 val >>= 8;
61 }
62
63 return n;
64}
65
66uint64_t
67coap_decode_var_bytes8(const uint8_t *buf, size_t len) {
68 unsigned int i;
69 uint64_t n = 0;
70 for (i = 0; i < len && i < sizeof(uint64_t); ++i)
71 n = (n << 8) + buf[i];
72
73 return n;
74}
75
76unsigned int
77coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val) {
78 unsigned int n, i;
79 uint64_t tval = val;
80
81 for (n = 0; tval && n < sizeof(val); ++n)
82 tval >>= 8;
83
84 if (n > length) {
85 assert(n <= length);
86 return 0;
87 }
88 i = n;
89 while (i--) {
90 buf[i] = val & 0xff;
91 val >>= 8;
92 }
93
94 return n;
95}
int coap_flsll(long long j)
Definition: coap_encode.c:28
int coap_fls(unsigned int i)
Definition: coap_encode.c:21
Pulls together all the internal only header files.
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:67
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition: coap_encode.c:77