Imported Upstream version 0.9.1
[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 #ifndef NDEBUG
10 #  include <stdio.h>
11 #endif
12
13 #include "config.h"
14 #include "encode.h"
15
16 /* Carsten suggested this when fls() is not available: */
17 int coap_fls(unsigned int i)
18 {
19     int n;
20     for (n = 0; i; n++)
21         i >>= 1;
22     return n;
23 }
24
25 unsigned int coap_decode_var_bytes(unsigned char *buf, unsigned int len)
26 {
27     unsigned int i, n = 0;
28     for (i = 0; i < len; ++i)
29         n = (n << 8) + buf[i];
30
31     return n;
32 }
33
34 unsigned int coap_encode_var_bytes(unsigned char *buf, unsigned int val)
35 {
36     unsigned int n, i;
37
38     for (n = 0, i = val; i && n < sizeof(val); ++n)
39         i >>= 8;
40
41     i = n;
42     while (i--)
43     {
44         buf[i] = val & 0xff;
45         val >>= 8;
46     }
47
48     return n;
49 }
50