将 Char 缓冲区转换为短裤数组

标签 c casting char buffer short

我有一个由 API 函数填充的 char * 缓冲区。我需要获取该指针包含的数据,将其转换为无符号短裤并将其转换为网络 (htons()) 格式以通过 UDP 发送。这是我的代码(由于某些原因并非全部)

下面的代码可以工作,但另一端的数据是坏的(不是短裤或网络翻译)

    char * pcZap;
    while(1)
    {
        unsigned short *ps;
        unsigned short short_buffer[4096];

        write_reg(to start xfer);
        return_val = get_packet(fd, &pcZap, &uLen, &uLob);
        check_size_of_uLen_and_uLob(); //make sure we got a packet

        // here I need to chage pcZap to (unsigned short *) and translate to network            

        sendto(sockFd,pcZap,size,0,(struct sockaddr *)Server_addr,
               sizeof(struct sockaddr));
        return_val = free_packet(fd, pcZap);
        thread_check_for_exit();
    }

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

假设您的缓冲区中有 4080 个字节由 16 位样本组成,这意味着您的缓冲区的 4080 字节中总共有 2040 个 16 位样本(16 字节为 header 保留)。因此,您可以执行以下操作:

#define MAXBUFSIZE 4096
#define MAXSHORTSIZE 2040

unsigned char pcZap[MAXBUFSIZE];
unsigned ushort[MAXSHORTSIZE];

//get the value of the returned packed length in uLen, and the header in uLob

unsigned short* ptr = (unsigned short*)(pcZap + uLob);
for (int i=0; i < ((uLen - uLob) / 2); i++)
{
    ushort[i] = htons(*ptr++);
}

现在您的 ushort 数组将由 pcZap 数组中的原始值转换而来的网络字节顺序 unsigned short 值组成。然后,当您调用 sendto() 时,请确保使用 ushort 中的值,而不是 pcZap 中的值。

关于将 Char 缓冲区转换为短裤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7691925/

相关文章:

c++ - 是否可以将派生类数组截断为 C++ 中的基类数组?

c - 输入带有不可打印字符的字符串

c - 如何从 Linux 下用 C 编写的 udf 返回 firebird 时间戳

比较字符

c - C 中字符串指针的增加值

java - 在非单例 bean 上的 Spring 代理上修复 BeanNotOfRequiredTypeException?

mysql - SQL 将 int 转换为日期时间

更改函数内变量的值

c - C 编程中的二维字符数组

c - 如何获取字符串的第n个字符?