简体   繁体   中英

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.

#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. 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.

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. Is there a better alternative to putchar I can use which will correctly wrap around?

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.

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. You can read any value in memory as an array of bytes, and you can use fwrite to write an array of bytes.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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