Writing a stream of 9 bit values as bytes to a file in C

后端 未结 2 2052
眼角桃花
眼角桃花 2021-01-25 05:54

I have an array with integer values from 0-511 (9 bits max). I am trying to write this to a file with fwrite.

For Example, with the array:

[         


        
2条回答
  •  粉色の甜心
    2021-01-25 06:30

    Ok, so did it using bit shifting, oring (can also do with *, '+', % and /) but shift is more appropriate / readable, imo.

    // Your data, n is the number of 9-bits values
    uint16_t dat[] = { 257, 258, 259 };
    int i,n = sizeof(dat)/sizeof(*dat);
    
    // out file
    FILE *fp = fopen("f8.bin","w");
    
    uint16_t one = 0;
    int shift = 0;
    uint8_t b;
    
    // main loop
    for(i=0 ; i>(8-shift);     // Move the remaining MSb to the right
        shift = (shift+9) % 8;       // next shift
        fwrite(&b, 1, 1, fp);        // write our b byte
    }
    // remainder, always have a remainder
    fwrite(&one, 1, 1, fp);
    fclose(fp);
    

    Had fun :-)

提交回复
热议问题