1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* 3 * Copyright (c) 2021 SUSE LLC <mdoucha@suse.cz> 4 * 5 * Convert bytes from standard input to hexadecimal representation. 6 * 7 * Parameters: 8 * -d Convert hexadecimal values from standard input to binary representation 9 * instead. 10 */ 11 12 #include <stdio.h> 13 #include <unistd.h> 14 decode_hex(void)15int decode_hex(void) 16 { 17 int ret; 18 unsigned int val; 19 20 while ((ret = scanf("%2x", &val)) == 1) 21 putchar(val); 22 23 return ret != EOF || ferror(stdin); 24 } 25 encode_hex(void)26int encode_hex(void) 27 { 28 int val; 29 30 for (val = getchar(); val >= 0 && val <= 0xff; val = getchar()) 31 printf("%02x", val); 32 33 return val != EOF || ferror(stdin); 34 } 35 main(int argc,char ** argv)36int main(int argc, char **argv) 37 { 38 int ret, decode = 0; 39 40 while ((ret = getopt(argc, argv, "d"))) { 41 if (ret < 0) 42 break; 43 44 switch (ret) { 45 case 'd': 46 decode = 1; 47 break; 48 } 49 } 50 51 if (decode) 52 return decode_hex(); 53 else 54 return encode_hex(); 55 } 56