sprintf原始字节转换为C中的字符串?

问题描述 投票:1回答:1

我正在使用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
n += strcpy(response, "HTTP/1.1 200\r\n\r\n");
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”)是否有像虚构的[ C0]这样做是什么?

c string format-specifiers
1个回答
0
投票

是否有像虚构的%4b这样的格式说明符?

[不,没有,您的方法很好。我建议使用%4b和一些检查来避免缓冲区溢出,并添加ex。 snprintf检查平台是否使用大端字节序和类似环境以及错误处理,并避免进行未定义的行为检查。

也就是说,您可以多次使用static_assert(sizeof(int) == 4, "") printf说明符,例如%c打印4个字节。您可以将其包装在宏中并执行:

"%c%c%c%c", ((char*)&x)[3], ((char*)&x)[2], ((char*)&x)[1], ((char*)&x)[0]
© www.soinside.com 2019 - 2024. All rights reserved.