从二进制文件为十六进制用C转换 [英] Conversion from binary file to hex in C

查看:145
本文介绍了从二进制文件为十六进制用C转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试写一些简单的程序来将文件上传到我的服务器。我想,以二进制文件转换为十六进制。我已经写了一些东西,但它不能正常工作。

I am trying to write some simple program to uploading files to my server. I' d like to convert binary files to hex. I have written something, but it does not work properly.

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

static int bufferSize = 1024;
FILE *source;
FILE *dest;

int n;
int counter;

int main() {
    unsigned char buffer[bufferSize];
    source = fopen("server.pdf", "rb");
    if (source) {
        dest = fopen("file_test", "wb");

        while (!feof(source)) {
            n = fread(buffer, 1, bufferSize, source);
            counter += n;
            strtol(buffer, NULL, 2);
            fwrite(buffer, 1, n, dest);
        }
    }
    else {
        printf("Error");
    }
    fclose(source);
    fclose(dest);
}

我使用 strtol将以二进制转换做十六进制。调用此code后,我仍然有奇怪的字符在我file_test文件。

I use strtol to convert binary do hex. After invoking this code I have still strange characters in my file_test file.

我想上传服务器上的文件,例如 PDF文件。但是首先我必须写一个程序,将这个文件转换为十六进制文件。我想,在十六进制文件中的行的长度将等于1024之后,我会上传逐行该文件符合的 PL / SQL

I' d like to upload a file on server, for example a PDF file. But firstly I have to write a program, that will convert this file to a hex file. I'd like that the length of a line in hex file would be equal 1024. After that, I will upload this file line by line with PL/SQL.

推荐答案

您code是飞驰的困惑。

Your code is fantastically confused.

这是读取数据,然后做就可以了与strtol()通话,为2的基地,然后的忽略返回值。什么是点在那?

It's reading in the data, then doing a strtol() call on it, with a base of 2, and then ignoring the return value. What's the point in that?

要转换数据,以十六进制字符串的第一个字节加载,你应该使用这样的:

To convert the first loaded byte of data to hexadecimal string, you should probably use something like:

char hex[8];

sprintf(hex, "%02x", (unsigned int) buffer[0] & 0xff);

然后写十六进制

输出文件。您需要为加载的所有字节做到这一点,当然,不只是缓冲[0]

此外,作为一个小点,你不能叫的feof()您已经尝试读取文件之前。最好是不要使用的feof(),而是检查的返回值 FREAD的的()到失败时检测到。

Also, as a minor point, you can't call feof() before you've tried reading the file. It's better to not use feof() and instead check the return value of fread() to detect when it fails.

这篇关于从二进制文件为十六进制用C转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆