-
Notifications
You must be signed in to change notification settings - Fork 0
/
byteStuffing.c
72 lines (57 loc) · 1.71 KB
/
byteStuffing.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
char* stuffBytes(char *msg, int *msg_size)
{
char* stuffed_msg;
//malloc stuffed message
stuffed_msg = (char *) malloc(sizeof(char) * (*msg_size));
memcpy(stuffed_msg,msg,(*msg_size));
int i = 0;
int j = 0;
for(i = 0; i < (*msg_size); i++)
{
if (stuffed_msg[i] == 0x7d)
{
(*msg_size)++;
stuffed_msg = realloc(stuffed_msg, (*msg_size));
memmove(&stuffed_msg[i+2], &stuffed_msg[i+1], sizeof(char) * ((*msg_size)-i-2));
stuffed_msg[i] = 0x7d;
stuffed_msg[i+1] = 0x5d;
}
else if (stuffed_msg[i] == 0x7e)
{
(*msg_size)++;
stuffed_msg = realloc(stuffed_msg, (*msg_size));
memmove(&stuffed_msg[i+2], &stuffed_msg[i+1], sizeof(char) * ((*msg_size)-i-2));
stuffed_msg[i] = 0x7d;
stuffed_msg[i+1] = 0x5e;
}
}
return stuffed_msg;
}
char* deStuffBytes(char *msg, int *msg_size)
{
char *destuffed_msg;
//malloc destuffed mesage
destuffed_msg = (char *) malloc (sizeof(char) * (*msg_size));
memcpy(destuffed_msg,msg,(*msg_size));
int i;
for (i = 0; i < (*msg_size); i++)
{
if (destuffed_msg[i] == 0x7d)
{
if (destuffed_msg[i+1] == 0x5d)
{
(*msg_size)--;
destuffed_msg = realloc(destuffed_msg, (*msg_size-1));
memmove(&destuffed_msg[i+1], &destuffed_msg[i+2], (*msg_size)-i-1);
}
else if(destuffed_msg[i+1] == 0x5e)
{
(*msg_size)--;
destuffed_msg = realloc(destuffed_msg, (*msg_size-1));
memmove(&destuffed_msg[i+1], &destuffed_msg[i+2], (*msg_size)-i-1);
destuffed_msg[i] = 0x7e;
}
}
}
return destuffed_msg;
}