在运行时将值添加到unsigned char数组

时间:2012-03-01 04:13:38

标签: c

我想将* .bmp打印到收据打印机。因为我正在读取循环内的像素值(十六进制),然后我需要使用printer命令追加读取值以进行打印然后写入打印机。 printer api仅接受unsigned char。现在我将像素值写入临时文件。如何使用打印机命令构造unsigned char数组。

unsigned char printcommand [] = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67 };

int len=sizeof(printcommand)/sizeof(unsigned char);
printf("Length Of Array=%d\n", len);

result = C56_api_printer_clear (iPrinter);


/*----------READ RASTER DATA----------*/
for(r=0; r<=originalImage.rows - 1; r++) {
    for(c=0; c<=originalImage.cols - 1; c++) {
        /*-----read data and print in (row,column) form----*/
        fread(pChar, sizeof(char), 1, bmpInput);
                // here instead of writing to file i need to append to printercommand[]
        fprintf(rasterOutput, "0x%x,", *pChar);
    }
        // here i need to write to the printer as C56_api_printer_write(iPrinter, printcommand, sizeof(printcommand), 1000);
    fprintf(rasterOutput, "\n");
}

// close the printer

任何想法如何在C中执行此操作?

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

你应该做的是找到位图的宽度和高度,然后找到malloc一个宽度*高度的内存块,然后将每个索引设置为正确的值。

打印机采用何种格式进行打印?信吗?有点吵?你还在使用什么类型的位图? 1位? 24位?

答案 1 :(得分:0)

声明

unsigned char printcommand [] = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67 };

创建一个正好7个字节的数组。你不能追加它,因为它会写入数组外的内存,并可能覆盖其他数据和/或代码。

您可以做的是将数组声明为更大的大小,如下所示:

unsigned char printcommand [128] = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0 };

现在数组是128个字节,从你的七个字节开始,其余的用零填充(初始化列表中的最后一个值用于数组的其余部分。)要附加到此数组,你需要跟踪下一个要追加的位置,或者大小。 像这样:

int printcommand_current_size = 7;

/* ... */

/* Append a new byte to the array */
printcommand[printcommand_current_size++] = *pChar;

最后一个语句向数组添加一个新字节,并增加了大小。

您应该添加一项检查,以确保不会尝试超出数组的限制。

答案 2 :(得分:0)

您可以分配一个适当长度的unsigned char[]缓冲区。您可以一次读取整行而不是逐个字符。类似的东西:

unsigned char *oneColumn;
/* oneColumn needs enough room for the print command + data */
oneColumn = (unsigned char *)malloc(originalImage.cols - 1 + len);

/* start off the buffer with the print command */
memcpy(oneColumn, printcommand, len);

/* get one row of data from the file */
fread(oneColumn+len, sizeof(char), originalImage.cols - 1, bmpInput);

然后您可以将缓冲区数据发送到打印命令。

(这是基于您的示例代码中的假设 - 每个“像素”一个字节)