diff --git a/Makefile b/Makefile index 8e5c9fb3..33e31583 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,9 @@ PROGRAM:=coap VERSION:=0.01 -SOURCES:= pdu.c net.c +SOURCES:= pdu.c net.c encode.c OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) -HEADERS:=coap.h debug.h pdu.h net.h +HEADERS:=coap.h debug.h pdu.h net.h encode.h CFLAGS:=-g -Wall -std=c99 -pedantic DISTDIR=$(PROGRAM)-$(VERSION) FILES:=main.c Makefile $(SOURCES) $(HEADERS) diff --git a/encode.c b/encode.c new file mode 100644 index 00000000..88f6bb45 --- /dev/null +++ b/encode.c @@ -0,0 +1,32 @@ +/* encode.c -- encoding and decoding of CoAP data types + * + * (c) 2010 Olaf Bergmann + */ + +#ifndef NDEBUG +# include +#endif + +#include "encode.h" + +unsigned int +coap_pseudo_encode( unsigned int val ) { + unsigned int e = 0; + + if ( val < HIBIT ) + return val; + + if ( val > MAX_VALUE ) { +#ifndef NDEBUG + fprintf(stderr, "cannot encode value %u\n", val); +#endif + return ( 1 << N ) - 1; + } + + while ( HIBIT < (val & ~0xff) ) { + val = val >> 1; + e += 1; + } + + return (val & ~EMASK) | e; +} diff --git a/encode.h b/encode.h new file mode 100644 index 00000000..ee68b324 --- /dev/null +++ b/encode.h @@ -0,0 +1,24 @@ +/* encode.h -- encoding and decoding of CoAP data types + * + * (c) 2010 Olaf Bergmann + */ + +#ifndef _COAP_ENCODE_H_ +#define _COAP_ENCODE_H_ + +#include "encode.h" + +#define N 8 +#define E 4 +#define HIBIT (1 << (N - 1)) +#define EMASK ((1 << E) - 1) +#define MMASK ((1 << N) - 1 - EMASK) +#define MAX_VALUE ( (1 << N) - (1 << E) ) * (1 << ((1 << E) - 1)) + +/* internal function, better use macro COAP_PSEUDOFP_ENCODE() instead */ +unsigned int coap_pseudo_encode( unsigned int val ); + +#define COAP_PSEUDOFP_ENCODE(r) coap_pseudo_encode( (r) ) +#define COAP_PSEUDOFP_DECODE(r) (r < HIBIT ? r : (r & MMASK) << (r & EMASK)) + +#endif /* _COAP_ENCODE_H_ */