Imported Upstream version 1.0.0
[platform/upstream/iotivity.git] / resource / csdk / connectivity / lib / libcoap-4.1.1 / encode.c
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 #include "config.h"
10
11 #if defined(HAVE_ASSERT_H) && !defined(assert)
12 # include <assert.h>
13 #endif
14
15 #ifndef NDEBUG
16 #  include <stdio.h>
17 #endif
18
19 #include "config.h"
20 #include "encode.h"
21 #include "option.h"
22
23 /* Carsten suggested this when fls() is not available: */
24 int coap_fls(unsigned int i)
25 {
26     int n;
27     for (n = 0; i; n++)
28         i >>= 1;
29     return n;
30 }
31
32 unsigned int coap_decode_var_bytes(unsigned char *buf, unsigned int len)
33 {
34     unsigned int i, n = 0;
35     for (i = 0; i < len; ++i)
36         n = (n << 8) + buf[i];
37
38     return n;
39 }
40
41 unsigned int coap_encode_var_bytes(unsigned char *buf, unsigned int val)
42 {
43     unsigned int n, i;
44
45     for (n = 0, i = val; i && n < sizeof(val); ++n)
46         i >>= 8;
47
48     i = n;
49     while (i--)
50     {
51         buf[i] = val & 0xff;
52         val >>= 8;
53     }
54
55     return n;
56 }
57
58 bool coap_is_var_bytes(coap_option_def_t* def)
59 {
60     assert (def);
61
62     if('u' == def->type)
63     {
64         return 1;
65     }
66     else
67     {
68       return 0;
69     }
70 }