Plan 9 from Bell Labs’s /usr/web/sources/contrib/fgb/cmd/bitdump.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>

int index = 0;

void
dumpdata(char *name, uchar *buf, int n, int mask)
{
	int i, x;

	print("\nstatic uchar %s[%d] = {", name, n);
	for(i = 0; i < n; i++) {
		if(i%8 == 0)
			print("\n\t");
		x = buf[i];
		if(mask)
			x = x==index ? 0 : 255;
		print("%d, ", x);
	}
	print("\n};\n\n");
}

void
dump(int fd, char *name)
{
	uchar *buf;
	char *s;
	int i, n, size, nb, w, h;

	i = 0;
	size = 1024;

	buf = malloc(size);
	if(buf == nil){
    Memerror:
		fprint(2, "out of memory: %r\n");
		exits("memory");
	}
	while((n=read(fd, buf+i, size-i)) > 0){
		i += n;
		if(i == size){
			size *= 2;
			buf = realloc(buf, size);
			if(buf == nil)
				goto Memerror;
		}
	}
	buf = realloc(buf, i+1);
	if(buf == nil)
		goto Memerror;

	buf[i] = 0;
	n = i;

	if(!(buf[9]=='m' && buf[10]=='8')) {
		fprint(2, "%s: bad image format\n", name);
		exits("format");
	}
	w = atoi((char *)buf+36) - atoi((char *)buf+12);
	h = atoi((char *)buf+48) - atoi((char *)buf+24);
	nb = w*h;
	if(n != 5*12 + nb){
		fprint(2, "bad image length\n");
		exits("length");
	}
	print("#define %swidth %d\n", name, w);
	print("#define %sheight %d\n", name, h);

	dumpdata(name, buf+5*12, nb, 0);
	if(index){
		s = smprint("%smask", name);
		if(s == nil)
			goto Memerror;
		dumpdata(s, buf+5*12, nb, 1);
		free(s);
	}
}

void
main(int argc, char *argv[])
{
	char *status = "";
	char *p;
	int i, fd;

	ARGBEGIN{
	case 't':
		p = ARGF();
		if(p == nil)
			goto Usage;
		index = atoi(p);
		if(index <= 0)
			goto Usage;
		break;
	default:
    Usage:
		fprint(2, "usage: bitdump [-t index] [file...]\n");
		exits("usage");
	}ARGEND

	if(argc == 0)
		dump(0, "stdin");
	else{
		for(i=0; i<argc; i++){
			fd = open(argv[i], OREAD);
			if(fd < 0){
				perror(argv[i]);
				status = "can't open";
			}else{
				p = strrchr(argv[i], '.');
				if(p != nil)
					*p = 0;

				dump(fd, argv[i]);
				close(fd);
			}
		}
	}
	exits(status);
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.