gpt4 book ai didi

c - uint16_t uint8_t 还是 size_t?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:48:34 27 4
gpt4 key购买 nike

我想使用一个函数,该函数负责通过 write() 将“数据大小”和“数据”发送到特定的文件描述符。当记录长度等于 2 个字节时有效。但是,我想使用相同的函数来发送长度也等于 1 个字节的记录。

send_func(int port)
{
void *fd;
uint64_t fsize = 2517283;
uint64_t nbrBytes = 0;
uint16_t rsize;
int count;
ssize_t ret;
uint8_t Bsent = 0;

for (count = 1; nbrBytes < fsize; count++)
{
rsize = ((uint8_t*)fp)[nbrBytes];
rsize += ((((uint8_t*)fp)[nbrBytes + 1]) << 8) & 0xFF00;
nbrBytes += 2;

// send size
ret = write(port, rsize, 2);
if (ret != 2) {
return -1;
}
// send data
ret = write(port, ((unsigned char*)fp) + Bsent, rsize - Bsent);
if (ret < 0) {
return -1;
}
Bsent += ret;
}
}

send_func(int port)
{
void *fd;
uint64_t fsize = 2517283;
uint64_t nbrBytes = 0;
size_t rsize;
int count;
ssize_t ret;
uint8_t Bsent = 0;

for (count = 1; nbrBytes < fsize; count++)
{
if (mode == ONLY_1_BYTE) {
rsize = ((uint8_t*)fp)[nbrBytes];
rsize += ((((uint8_t*)fp)[nbrBytes + 1]));
nbrBytes += 1;

do {
// send data
ret = write(port, ((unsigned char*)fp) + Bsent, rsize - Bsent);
if (ret < 0) {
return -1;
}
Bsent += ret;
} while(Bsent < rsize)
}
else
{
rsize = ((uint8_t*)fp)[nbrBytes];
rsize += ((((uint8_t*)fp)[nbrBytes + 1]) << 8) & 0xFF00;
nbrBytes += 2;

// send size
ret = write(port, rsize, sizeof(uint16_t));
if (ret != 2) {
return -1;
}
}

do {
// send data
ret = write(port, ((unsigned char*)fp) + Bsent, rsize - Bsent);
if (ret < 0) {
return -1;
}
Bsent += ret;
} while(Bsent < rsize)
}
}

因为第二种情况只有1个长度字节,所以我主动去掉了字节序操作,在2个字节的情况下是强制的。

这是最好的练习方式吗?

最佳答案

您可以应用一些最佳实践来改进您发布的代码:

  • 不必担心优化流中的单个字节。没关系。您知道吗,除了您的有效负载之外,每个以太网帧还需要大约 60 字节的开销?
  • 不要手动进行字节序交换。使用 htons() 等内置函数。
  • 您需要考虑“短写入”,其中 write() 的返回值小于您尝试发送的值。发生这种情况时,您需要循环并再次调用 write() 而无需重新发送长度前缀。

关于c - uint16_t uint8_t 还是 size_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34293606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com