0

Such a silly question but I've been trying for at least 15 minutes already and it's late at night. How to use printf in bash to convert a binary number to hex? Here's what I've tried:


$ printf %x 11  # sanity check
b

$ printf %x 0b11
bash: printf: 0b11: invalid number
0

$ printf %x b11
bash: printf: b11: invalid number
0

$ printf %x 0#11
bash: printf: 0#11: invalid number
0

$ printf %x 'b11'
bash: printf: b11: invalid number
0

$ nano main.c && g++ main.c && ./a.out 
3

 1 #include <stdio.h>                                                              
 2                                                                                 
 3                                                                                 
 4 // In this file:                                                                
 5 //    - base2 to base16 converter                                              
 6                                                                                 
 7                                                                                 
 8 int main()                                                                      
 9 {                                                                               
10     printf("%x", 0b11);                                                         
11 }                                                                               
12   
Vorac
  • 2,957
  • 8
  • 36
  • 53
  • google `binary number bash` to get `2#11` – jsotola Aug 08 '23 at 23:43
  • @jsotola tried that as well `$ printf %x 2#11` `bash: printf: 2#11: invalid number` `2` – Vorac Aug 09 '23 at 00:12
  • 2
    Try `printf '%x' "$((2#11))"` - see for example [Binary to hexadecimal and decimal in a shell script](https://unix.stackexchange.com/questions/65280/binary-to-hexadecimal-and-decimal-in-a-shell-script) – steeldriver Aug 09 '23 at 00:24
  • 1
    @Vorac Yikes, Bash overloaded the comment character? – Kaz Aug 09 '23 at 00:38
  • @Kaz it's late at night, I told you. 'steeldriver' solved it, no idea how my searches didn't land on that question. Nice sarcasm btw. Would You advise to delete the question or mark it as a duplicate? – Vorac Aug 09 '23 at 01:27
  • 1
    @Kaz Bash overloads dozens of characters -- consider `(` or `*`. `#` is only a comment when not escaped, quoted or preceded by a space. – Paul_Pedant Aug 09 '23 at 07:11
  • 1
    One way not in the duplicate answer : `dc -e "16 o 2 i 11011001 p"` gives `D9`. `dc` supports any combination of input radix `2-9,A-F`, output radix `2-huge`. – Paul_Pedant Aug 09 '23 at 07:26
  • @Paul_Pedant was asking explicitly about `printf` but Your comment indicates `dc` and probably `bc` are just fine(er). You might consider adding an answer to the linked question. – Vorac Aug 09 '23 at 15:51

0 Answers0