gpt4 book ai didi

c - 如何将 for 循环中的整数作为十六进制值输出到文件

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:25 27 4
gpt4 key购买 nike

我试图用一些 C 代码创建一个 .pam 图像,但 fwrite 函数只将对应的 ASCII 码写入文件,而不是十六进制值。

文件的头部需要是 ASCII,实际的图像数据需要只是 rgb 和 alpha 的十六进制值。

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

int main() {

FILE *out;

out = fopen("C:/Users/entin/Desktop/write.pam", "wb+");

if (out == NULL) {
printf("Unable to access file.\n");
} else {

//everything concerning the head

//buffer the head to not get an overflow
unsigned char headbuf[100];
sprintf(headbuf, "P7\nWIDTH 255\nHEIGHT 255\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n");

//reduce head to nessesary length so it dosent output useless NULL's
int len = strlen(headbuf);
unsigned char head[len];
sprintf(head, "P7\nWIDTH 255\nHEIGHT 255\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n");

//write head to file
fwrite(head, sizeof (head), 1, out);


//initiating pixel values
unsigned char buf[8];
int r = 0; //AA
int g = 0; //BB
int b = 0; //CC
int a = 255; //DD

//for now just change the red and green values
for (r = 0; r <= 255; r++) {
for (g = 0; g <= 255; g++) {

//coppy pixel data to buffer
sprintf(buf, "%02X%02X%02X%02X", r, g, b, a);

//write buffer to head
fwrite(buf, sizeof (buf), 1, out);
}
}

}
fclose(out);
printf("fin");
getchar();
return (EXIT_SUCCESS);
}

它输出我想要的头部,但像素值也写在它们的 ASCII 值中

它输出 ENDHDR\nAABBCCDD

作为。45 4E 44 48 44 52 0A 41 41 42 42 43 43 44 44

它应该像这样输出:45 4E 44 48 44 52 0A AA BB CC DD

最佳答案

我修正了我的代码,只是将值写成对应的 ASCII 码。

这里是固定代码

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

int main() {

FILE *out;

out = fopen("C:/Users/entin/Desktop/write.pam", "wb+");

if (out == NULL) {
printf("Unable to access file.\n");
} else {

//head
fprintf(out, "P7\nWIDTH 255\nHEIGHT 255\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n");

//initiating pixel values
int r = 0; //red
int g = 0; //green
int b = 255; //blue
int a = 255; //alpha

//for now just change the red and green values
for (r = 0; r <= 255; r++) {
for (g = 0; g <= 255; g++) {

//call the numbers as theirr ASCII counterpart and print them
fprintf(out, "%c%c%c%c", r, g, b, a);

}
}

}
fclose(out);
printf("fin");
getchar();
return (EXIT_SUCCESS);
}

这是第一个结果

red/green variation, blue/alpha fix255

关于c - 如何将 for 循环中的整数作为十六进制值输出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55514058/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com