How to send message FROM Chrome extension TO Native app?

流过昼夜 提交于 2019-12-03 21:43:11

To read the json-data from stdin:

int _tmain(int argc, _TCHAR* argv[])
{

unsigned int length = 0;
//read the first four bytes (=> Length)
for (int i = 0; i < 4; i++)
{
    length += getchar();
}

//read the json-message
string msg = "";
for (int i = 0; i < length; i++)
{
    msg += getchar();
}
}

As someone mentioned in the comments, the provided solution won't work if the length is greater than 255. For example, if actual length is 296 (binary 00000001 00101000) the solution presented earlier will produce 41 => 00000001 + 00101000 = 1 + 40 = 41.

The number of byte that is read must be taken into consideration. In this example, the correct way to calculate the length is 1*(2^8) + 40 = 296. So the correct solution might be:

unsigned int length = 0;

//read the first four bytes
for (int i = 0; i < 4; i++) {
  int read_char = getchar();
  length += read_char * (int) pow(2.0, i * 8);
}

Better solution based on shifting of bits and bit operations is presented below (perhaps little bit harder to understand but for sure neater):

unsigned int length = 0;

for (int i = 0; i < 4; i++) {
  unsigned int read_char = getchar();
  length = length | (read_char << i * 8);
}

It is important to notice that getchar() returns int that is cast to unsigned int before performing bit OR with current value of length (int has one bit reserved for sign, unsigned int doesn't).

Now, I am not sure about potential big/little endian problems that may appear here as I haven't tested this solution on different architectures. I hope someone with more experience can comment on this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!