我想对于具有Common Lisp经验的人来说,这是一个简单的问题。对于刚开始使用LISP的我来说,不算什么。
如您在下面的下一个片段中看到的,我创建了一个800 x 600类型的array UNSIGNED BYTE
。
(defun test-binary-save ()
(let*
((width 800)
(height 600)
(arr (make-array (list width height)
:element-type '(mod 256)
:initial-element 0)))
(utilities::save-array-as-pgm "test.pgm" arr)))
我的实用程序包中的功能应该以P5 PGM
do格式写入。
(defun save-array-as-pgm (filename buffer)
"Writes a byte array as a PGM file (P5) to a file."
(with-open-file
(stream filename
:element-type '(unsigned-byte 8)
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(let*
((dimensions (array-dimensions buffer))
(width (first dimensions))
(height (second dimensions))
(header (format nil "P5~A~D ~D~A255~A"
#\newline
width height #\newline
#\newline)))
(loop
:for char :across header
:do (write-byte (char-code char) stream))
;(write-sequence buffer stream) <<-- DOES NOT WORK - is not of type SEQUENCE
))
filename)
具有相同功能的等效(有效)C函数如下所示。
static
int
save_pgm
( const char* filename
, size_t width
, size_t height
, const uint8_t* pixels
)
{
if(NULL == filename)
return 0;
if(NULL == pixels)
return 0;
FILE *out = fopen(filename, "wb");
if(NULL != out)
{
fprintf(out, "P5\n%zu %zu\n255\n", width, height);
size_t nbytes = width * height;
fwrite(pixels,1,nbytes,out);
fclose(out);
return 1;
}
return 0;
}
谁能告诉我如何修复save-array-as-pgm
函数,最好是一次性编写数组,而不是使用循环和(write-byte (aref buffer y x) stream)
?
在我决定在这里问这个问题之前,我在Google上搜索了很多,只找到了一些做一些花哨的二进制文件的包的引用-但这是一个简单的案例,我正在寻找一个简单的解决方案。
Common Lisp支持置换数组:
CL-USER 6 > (let ((array (make-array (list 3 4)
:initial-element 1
:element-type 'bit)))
(make-array (reduce #'* (array-dimensions array))
:element-type 'bit
:displaced-to array))
#*111111111111
置换后的阵列本身没有存储,但是使用另一个阵列的存储。它可以具有不同的尺寸。
现在有一个问题,Lisp实现可以通过置换后的数组访问数组的效率如何。
@BitTicker在优化写序列时,还应考虑先定义1D数组,然后将2D数组移给它(带有sbcl的小基准值,但to方法之间的时间没有显着差异)