【发布时间】:2020-01-24 20:27:29
【问题描述】:
我通过 C 中的线路发送一些原始字节(使用 HTTP)。我目前正在这样做:
// response is a large buffer
int n = 0; // response length
int x = 42; // want client to read x
int y = 43; // and y
// write a simple HTTP response containing a 200 status code then x and y in binary format
strcpy(response, "HTTP/1.1 200\r\n\r\n");
n += 16; // status line we just wrote is 16 bytes long
memcpy(response + n, &x, sizeof(x));
n += sizeof(x);
memcpy(response + n, &y, sizeof(y));
n += sizeof(y);
write(client, response, n);
在 JavaScript 中,然后我使用如下代码读取这些数据:
request = new XMLHttpRequest();
request.responseType = "arraybuffer";
request.open("GET", "/test");
request.onreadystatechange = function() { if (this.readyState === XMLHttpRequest.DONE) { console.log(new Int32Array(this.response)) } }
request.send();
它应该打印[42, 43]。
我想知道是否有更优雅的方法可以在服务器端执行此操作,例如
n += sprintf(response, "HTTP/1.1 200\r\n\r\n%4b%4b", &x, &y);
%4b 是一个虚构的格式说明符,它只是说:将该地址中的 4 个字节复制到字符串中(即“*\0\0\0”)是否有像虚构的格式说明符%4b 做这样的事情?
【问题讨论】:
-
sprintf用于字符串。即 -char数组以\0结尾。所以不,它不适合任意二进制数据。 -
我不这么认为。
sprintf()通常用于创建可打印的字符串,而不是二进制。 -
那些
memcpy调用将使您的代码依赖于字节序。 -
如果要发送二进制数据,应该使用定义明确的序列化格式。
-
附加
"*\0\0\0"将终止第一个 '\0' 处的字符串 -sprintf()并不真正适合此目的。
标签: c string format-specifiers