unit 81 심사문제, 집에서는 잘 되는데 왜 통과 못하는지 잘 모르겠어요.
아래는 소스 입니다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#pragma pack(push, 1)
typedef struct _BITMAPFILEHEADER {
unsigned short bfType;
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
} BITMAPFILEHEADER;
typedef struct _BITMAPINFOHEADER {
unsigned int biSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned int biCompression;
unsigned int biSizeImage;
int biXPersPerMeter;
int biYPersPerMeter;
unsigned int biClrUsed;
unsigned int biClrImprotant;
} BITMAPINFOHEADER;
typedef struct _RGBTRIPLE {
unsigned char rgbtBlue;
unsigned char rgbtGreen;
unsigned char rgbtRed;
} RGBTRIPLE;
#pragma pack(pop)
#define PIXEL_SIZE 3
#define PIXEL_ALIGN 4
int main()
{
FILE* fpBmp;
FILE* fpTxt;
BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;
unsigned char* image;
int size;
int width, height;
int padding;
char ascii[] = { '9','8', '7', '6', '5', '4', '3', '2', '1', '0', ' ' };
fpBmp = fopen("sample.bmp", "rb");
if (fpBmp == NULL)
return 0;
if (fread(&fileHeader, sizeof(BITMAPFILEHEADER), 1, fpBmp) < 1)
{
fclose(fpBmp);
return 0;
}
if (fileHeader.bfType != 'MB')
{
fclose(fpBmp);
return 0;
}
if (fread(&infoHeader, sizeof(BITMAPINFOHEADER), 1, fpBmp) < 1)
{
fclose(fpBmp);
return 0;
}
if (infoHeader.biBitCount != 24)
{
fclose(fpBmp);
return 0;
}
size = infoHeader.biSizeImage;
width = infoHeader.biWidth;
height = infoHeader.biHeight;
padding = (PIXEL_ALIGN - (width * PIXEL_SIZE) % PIXEL_ALIGN) % PIXEL_ALIGN;
if (size == 0)
{
size = (width * PIXEL_ALIGN + padding) * height;
}
image = malloc(size);
fseek(fpBmp, fileHeader.bfOffBits, SEEK_SET);
if (fread(image, size, 1, fpBmp) < 1)
{
fclose(fpBmp);
return 0;
}
fclose(fpBmp);
//fpTxt = fopen("sample.txt", "w");
fpTxt = stdout;
if (fpTxt == NULL)
{
free(image);
return 0;
}
for (int y = height - 1; y >= 0; y--)
{
for (int x = 0; x < width; x++)
{
int index = (x * PIXEL_SIZE) + (y * (width * PIXEL_SIZE)) + (padding * y);
RGBTRIPLE* pixel = (RGBTRIPLE*)&image[index];
unsigned char blue = pixel->rgbtBlue;
unsigned char green = pixel->rgbtGreen;
unsigned char red = pixel->rgbtRed;
unsigned char gray = (red + green + blue) / PIXEL_SIZE;
char c = ascii[gray * sizeof(ascii) / 256];
fprintf(fpTxt, "%c", c);
}
fprintf(fpTxt, "\n");
}
fclose(fpTxt);
free(image);
return 0;
}
모양은 나오는데 중간에 값을 변환하는 과정이 틀린 것 같습니다.
문의한 코드는 sample.bmp에 대해서 첫 번째 줄의 텍스트만 살펴보면
65555555555554246644222222233433444444454323333222643355555566544433345565544334
문제의 예시에서 첫 번째 줄의 출력은 다음과 같습니다.
55555555435532112334554453222225335566543334555433