0

First, I use Python's read method to read a file,and print binary data of the file. The python code is :

aaa = open('D:\\CbProject\\testphoto2.jpg','rb')

a = aaa.read()
print(a)  #十六进制显示 二进制byte类型数据
print(len(a))  #39038

Python can display binary data of files in hexadecimal.Data type is [bytes]. The python result is : enter image description here

This seems normal,as you can see, the binary form of the file is “\xff \xd8 \xff \xe0 ......” Next, I use the C language's FREAD and read methods to read the file and print its binary form.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MYSIZE 39038

int main(void)
{

    FILE *fp;

    if((fp = fopen("D:\\CbProject\\testphoto2.jpg", "rb")) == NULL) {
        fprintf(stderr, "can't open file\n");
        exit(1);
    }

    char buffer[MYSIZE];
    if(fread(buffer, sizeof(buffer), 1, fp) != 1) {
        fprintf(stderr, "read failed");
        exit(1);
    }

    for (int i = 0; i < sizeof(buffer); i++) {
        printf("%2x  ", buffer[i]);
    }
    fclose(fp);
    return(0);
}


but the c result is : enter image description here

why? I have a lot of questions.First of all, the char of C language can only store one byte, but the display of many data is obviously larger than one byte.One byte equals 0xff.Why are there so many f's here. %2x ,Why can I print a 1, a 2, a 3...?

kireirain
  • 35
  • 5
  • 2
    For variadic functions any integer parameter that is "less" than `int` is automatically promoted to `int`. For signed values this includes sign extension. If you want to use with raw data, don't use `char` but `unsigned char` or `uint8_t`. Value `-2` is represented as `0xFE` which is extended to `0xFFFFFFFE`. – Gerhardh Jun 13 '22 at 09:18
  • 1
    Besides that, please do not post pictures of plain text. Instead copy&paste as formatted text. Also there is no need to include tons of text if a few numbers are sufficient to show your result. – Gerhardh Jun 13 '22 at 09:19

0 Answers0