我正在开发一个应用程序,我们将从客户端向服务器发送消息。该消息将包含64个字段,这些字段将通过TCP套接字连接复制到单个字符串中。该消息可能不包含所有64个字段。因此,为了解决这个问题,在所有这64个字段之前将有一个字段,该字段将是8个字符长,其将包含关于这些字段的信息,该字段存在哪个字段以及哪个字段不存在。我目前面临的问题是,如果我设置了第1,第3和第5位,那么该位图的长度将为1,并且将其复制到将要发送到服务器的字符串时仅1字符串到达那里,从第二个开始它曾经有' \ 0'。如果我把' 0'在其余的空间(从2到8)并设置其他字段(参见输出)。所以我的问题是,是否有任何方法我将字符串的长度保持为8,并且它也不会设置任何其他位,以便服务器可以提取正确的消息。再次迭代它,消息格式是8个字符的长位图,然后是64个字段的整个打包消息。
#include <iostream>
#include <cstring>
#define ISO_LEN 64
using namespace std;
int main()
{
int i ;
bool bitmap[ISO_LEN];
for(i = 0; i < ISO_LEN; i++)
{
bitmap[i] = false;
}
bitmap[1] = true; bitmap[3] = true; bitmap[5] = true;
unsigned char bmap[ISO_LEN/8 + 1];
for (int i = 0; i < ISO_LEN/8; bmap[i++] = 0);
for (int i = 0; i < ISO_LEN; i++)
{
if (bitmap[i])
{
bmap[i/8] |= (unsigned char)(0x80 >> (i%8));
}
}
// intentional effort to make the length exactly 8
int start = strlen(bmap);
for (int i = start; i < ISO_LEN/8 ; i++)
{
bmap[i] = '0';
}
// ends
char *sendee = new char[1000];
memcpy(sendee , bmap, ISO_LEN/8);
for (int i = 0; i < ISO_LEN; i++)
{
if (sendee[i/8] & ((unsigned char)0x80 >> (i % 8)))
{
cout<<i<<"th bit is true\n";
}
else
{
cout<<i<<"th bit is false\n";
}
}
return 0;
}
Output:
0th bit is false
1th bit is true
2th bit is false
3th bit is true
4th bit is false
5th bit is true
6th bit is false
7th bit is false
8th bit is false
9th bit is false
10th bit is true
11th bit is true
12th bit is false
13th bit is false
14th bit is false
15th bit is false
16th bit is false
17th bit is false
18th bit is true
19th bit is true
20th bit is false
21th bit is false
22th bit is false
23th bit is false
24th bit is false
25th bit is false
26th bit is true
27th bit is true
28th bit is false
29th bit is false
30th bit is false
31th bit is false
32th bit is false
33th bit is false
34th bit is true
35th bit is true
36th bit is false
37th bit is false
38th bit is false
39th bit is false
40th bit is false
41th bit is false
42th bit is true
43th bit is true
44th bit is false
45th bit is false
46th bit is false
47th bit is false
48th bit is false
49th bit is false
50th bit is true
51th bit is true
52th bit is false
53th bit is false
54th bit is false
55th bit is false
56th bit is false
57th bit is false
58th bit is true
59th bit is true
60th bit is false
61th bit is false
62th bit is false
63th bit is false