libcoap  4.2.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  * This file is part of the CoAP library libcoap. Please see
6  * README for terms of use.
7  */
8 
9 #ifndef NDEBUG
10 # include <stdio.h>
11 #endif
12 
13 #include "coap_config.h"
14 #include "coap.h"
15 #include "mem.h"
16 #include "encode.h"
17 
18 /* Carsten suggested this when fls() is not available: */
19 #ifndef HAVE_FLS
20 int coap_fls(unsigned int i) {
21  return coap_flsll(i);
22 }
23 #endif
24 
25 #ifndef HAVE_FLSLL
26 int 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 
35 unsigned int
36 coap_decode_var_bytes(const uint8_t *buf,unsigned int 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 
44 unsigned int
45 coap_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 
int coap_flsll(long long i)
Definition: encode.c:26
unsigned int coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val)
Encodes multiple-length byte sequences.
Definition: encode.c:45
int coap_fls(unsigned int i)
Definition: encode.c:20
#define assert(...)
Definition: mem.c:18
unsigned int coap_decode_var_bytes(const uint8_t *buf, unsigned int len)
Decodes multiple-length byte sequences.
Definition: encode.c:36
unsigned char uint8_t
Definition: uthash.h:79