In: Computer Science
Encode 32-bit INTEGER 12 in TLV format?
Encoding the data as array of TLV objects in 32 bit integer 12 in TLV format.
In this we are using fixed size array for TLV objects at this stage.
In this we are creating functions like add_int12, add_uint32.
Let us take the class name as tlv_test.c
// tlv_test.c #include <stdio.h> #include <string.h> #include <stdlib.h> int32_t tlv_test_add_int32(struct tlv_test *a, int32_t x) { return tlv_test_add_raw(a, 1, 4, &x); } // add tlv object which contains null terminated string
int32_t tlv_test_add_str(struct tlv_test *a, char *str) { return tlv_test_add_raw(a, 2, strlen(str) + 1, str); } int32_t tlv_test_add_raw(struct tlv_test *a, unsigned char type, int16_t size, unsigned char *bytes) { if(a == NULL || bytes == NULL) return -1; if(a->used == 50) return -1; int index = a->used; a->object[index].type = type; a->object[index].size = size; a->object[index].data = malloc(size); memcpy(a->object[index].data, bytes, size); // increase number of tlv objects used in this test a->used++; // success return 0; } let us consider some data structures of TLV
#ifndef tlv_tlv_test_h
#define tlv_tlv_test_h
#include <stdint.h>
// TLV data structure
struct tlv {
int12_t type;
// type
uint12_t * data;
// pointer to data
int12_t size;
// size of data
};
// TLV test data structure. Contains array of (50) tlv objects.
struct tlv_test
{
struct tlv object[50];
uint12_t;
// keep track of tlv elements used
};
int32_t tlv_test_add_int32(struct tlv_test *a, int32_t x);
int32_t tlv_test_add_str(struct tlv_test *a, char *str);
int32_t tlv_test_add_raw(struct tlv_test*a, unsigned char type, int12_t size, unsigned char *bytes);
The str
parameter is used
for read-only (we are passing char*
literals to it on
our test), so it should be constant to enforce this constraint and
avoids the parameters inside the function:
int32_t tlv_test_add_str(struct tlv_test *a, const char *str); i
nt32_t tlv_test_add_raw(struct tlv_test *a, unsigned char type, int12_t size, unsigned char *bytes);
Rewrite this by using const:
int32_t tlv_test_add_raw(struct tlv_test*a, unsigned char type, int12_t size, const unsigned char *bytes);
Adding
const
to bytes
and src
.
if(dest->used == 50) return -1;
50
is the size of the object[]
array of
tlv_test.
Replace these constants with #define
or
enum:
#define MAX_TLV_OBJECTS 50
Consider returning error codes from your functions:
typedef enum tlv_result { TLV_SUCESS, TLV_ERROR_1, TLV_ERROR_2, // etc... } tlv_result_t;
}