A
Angus
The sample code below simulates receiving a protocol message with a tlv
structure - type/length/data_value.
I am confused about copying the actual data to a temp string. I use *data++
= *mybytes; - but after the copy tyhe pointer points to the end of the
string - so I have to return back to the beginning of the string to be able
to eg print it out. In this sort of situation what coding pattern should I
be using to efficiently copy my data?
In a real situation there would probqably be another message after this
one - another tlv.
int main()
{
unsigned char buffer[] = {3,9,"123456789"};
//unsigned char buffer[] = {0,1,'A'};
unsigned char* mybytes = buffer;
bool done(false);
int type = *mybytes++; //dereferences ptr and returns value - then
increments ptr
int size = *mybytes++;
switch(type)
{
case 0:
{
char c = *mybytes++;
printf("char data type: %c, size: %i\n", c, size);
break;
}
case 3: //string type
{
char* data = (char*)malloc(size);
do
{
*data++ = *mybytes; // copies data
} while(*mybytes++);
for(int j = 0; j <= size; ++j)
*data--;
printf("char data type: %s, size: %i\n", data, size);
free(data);
break;
}
}
return 0;
}
structure - type/length/data_value.
I am confused about copying the actual data to a temp string. I use *data++
= *mybytes; - but after the copy tyhe pointer points to the end of the
string - so I have to return back to the beginning of the string to be able
to eg print it out. In this sort of situation what coding pattern should I
be using to efficiently copy my data?
In a real situation there would probqably be another message after this
one - another tlv.
int main()
{
unsigned char buffer[] = {3,9,"123456789"};
//unsigned char buffer[] = {0,1,'A'};
unsigned char* mybytes = buffer;
bool done(false);
int type = *mybytes++; //dereferences ptr and returns value - then
increments ptr
int size = *mybytes++;
switch(type)
{
case 0:
{
char c = *mybytes++;
printf("char data type: %c, size: %i\n", c, size);
break;
}
case 3: //string type
{
char* data = (char*)malloc(size);
do
{
*data++ = *mybytes; // copies data
} while(*mybytes++);
for(int j = 0; j <= size; ++j)
*data--;
printf("char data type: %s, size: %i\n", data, size);
free(data);
break;
}
}
return 0;
}