tomclegg.net |
Byteswap Posted June 25, 2004 Read words from standard input, swap byte order, write to standard output. /* byteswap.c */ /* tom clegg */ /* public domain */ #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> int main() { long bytesread, bufused, i; unsigned char buf[1048576], x; bufused=0; while(0 < (bytesread=read(STDIN_FILENO, buf+bufused, sizeof(buf)-bufused))) { bytesread+=bufused; for (i=0; i<(bytesread&~1); i+=2) { buf[i] ^= buf[i+1]; buf[i+1] ^= buf[i]; buf[i] ^= buf[i+1]; } write(STDOUT_FILENO, buf, bytesread&~1); if (bytesread&1) { bufused=1; buf[0]=buf[bytesread-1]; } else bufused=0; } if(bufused) write(STDOUT_FILENO, buf, bufused); exit(0); } |