'Load numbers from binary file represented with two bytes each
How could I load numbers from binary file which are nonnegative integers in the range 0-65535 represented by two bytes each?
Code:
#include <stdio.h>
#include <stdint.h>
int main() {
const char file[] = "numbers.dat";
FILE *fp = fopen(file, "rb");
uint16_t arr[100000];
int i;
int loaded=fread(arr, 2, 100000, fp);
printf("Loaded numbers: %d\n", loaded);
for (i = 0; i < loaded; i++)
printf("%d ", arr[i]);
fclose(fp);
return 0;
}
If I convert numbers 12142422342 to binary it would be: 11011001010010101110010 (I convert them one by one) and run this program I get output
Loaded numbers: 11
12593 12592 12337 12592 12592 12336 12337 12337 12593 12337 12592
How could I load numbers represented by two bytes each? Could you help me fix my code?
Correct output should be: 1 2 1 4 2 4 2 2 3 4 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
