简体   繁体   English

对于16位数据,我应该使用什么而不是putchar()?

[英]What should I use instead of putchar() for 16-bit data?

I am fairly new to C, and have written a simple program which generates a sine wave with a specified frequency and sample rate, and sends that to stdout as an unsigned 8-bit byte. 我对C很新,并编写了一个简单的程序,它生成一个具有指定频率和采样率的正弦波,并将其作为无符号的8位字节发送到stdout。

#include <stdio.h>
#include <math.h>
#include <stdint.h>

uint8_t sinco(int iCarrier, int iSampleRate, unsigned long ulIndex){return (sin(iCarrier * (2 * M_PI) * ulIndex / iSampleRate) * 127) + 128;}

void main(){    
    unsigned long t;
    const int iCarrier = 500;
    const int iSampleRate = 8000;

    for(t=0;;t++){
        putchar(sinco(iCarrier, iSampleRate, t));
    }
}

I realize that putchar() was not the most appropriate function, but it worked for what I needed at the time. 我意识到putchar()不是最合适的功能,但它适用于我当时需要的功能。 Now I am currently trying to modify the program to output an unsigned 16-bit number, but I'm not sure what to replace putchar() with. 现在我正在尝试修改程序以输出无符号的16位数,但我不知道用什么替换putchar()。

This is what I have so far: 这是我到目前为止:

#include <stdio.h>
#include <math.h>
#include <stdint.h>

uint16_t sinco(int iCarrier, int iSampleRate, unsigned long ulIndex){return (sin(iCarrier * (2 * M_PI) * ulIndex / iSampleRate) * 65535) + 65536;}

void main(){    
    unsigned long t;
    const int iCarrier = 500;
    const int iSampleRate = 8000;

    for(t=0;;t++){
        printf(%hu, sinco(iCarrier, iSampleRate, t));
    }
}

However once the value gets larger than 65,536, the program starts sending 32 bits to stdout. 但是,一旦该值大于65,536,程序就会开始向stdout发送32位。 Is there a better alternative to putchar I can use which will correctly wrap around? 是否有更好的替代putchar我可以使用哪个将正确包裹?

You want to output a value that is encoded in two bytes. 您希望输出以两个字节编码的值。 So output these two bytes successively. 所以连续输出这两个字节。 Which two bytes? 哪两个字节? It depends on how the 16-bit value is supposed to be encoded in two 8-bit values, ie on the endianness of the system that will read those two bytes. 它取决于16位值应该如何编码为两个8位值,即取决于将读取这两个字节的系统的字节序

Little-endian: 小端:

uint16_t w = sinco(…);
putchar(w & 0xff);
putchar((w >> 8) & 0xff);

Big-endian: 大端:

uint16_t w = sinco(…);
putchar((w >> 8) & 0xff);
putchar(w & 0xff);

If the system that reads the value has the same endianness as your CPU, then you can use a different strategy: write the value by dumping its memory contents. 如果读取该值的系统具有与CPU相同的字节顺序,则可以使用其他策略:通过转储其内存内容来写入该值。 You can read any value in memory as an array of bytes, and you can use fwrite to write an array of bytes. 您可以将内存中的任何值读取为字节数组,并且可以使用fwrite来写入字节数组。

uint16_t w = sinco(…);
fwrite(&w, 1, 2, stdout);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM