在 shell 脚本中将十进制数转换为十六进制和二进制 [英] Convert a decimal number to hexadecimal and binary in a shell script

查看:30
本文介绍了在 shell 脚本中将十进制数转换为十六进制和二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 file.txt 的每一行中都有一个十进制数:

I have a decimal number in each line of a file.txt:

    1
    2
    3

我正在尝试(现在太久了)编写一个单行脚本以输出其中每一行都有一个包含十进制、十六进制和二进制的列.为了简化任务,我们可以说原始数字以字节表示.所以最大值是255.

I am trying (for too long now) to write a one-liner script to have an output where each row has a column with the decimal, hexadecimal and the binary. To ease the task we can say that the original number is expressed in a byte. So the maximum value is 255.

  1. 我首先尝试将每个数字解码为前缀为 0 的二元数,以便获得 8 位模式:

  1. I first try to decode each number as a bynary with prepended 0 so to have an 8 bits pattern:

awk '{打印ibase=10;obase=2;"$1}' $1 |公元前 |xargs printf "%08d "

awk '{print "ibase=10;obase=2;" $1}' $1 | bc | xargs printf "%08d "

awk 语句中的外部 $1 是 file.txt.输出是:

where the outer $1 in the awk statement is file.txt. The output is :

00000001
00000010
00000011

  • 十六进制也一样,前面加一个 0

  • Same for hex with one prepended 0

    awk '{printf("0x%02x ", $1)}' $1

    awk '{printf("0x%02x ", $1)}' $1

    和以前一样.输出是:

    0x01
    0x02
    0x03
    

  • 嗯,小数点应该只是打印:

  • Well, the decimal should be just a print:

    1
    2
    3
    

  • 我想要的是一个我有的班轮:

    What I'd like to have is one liner where I have:

        1 00000001 0x01
        2 00000001 0x02
    

    所以基本上将 1. 2. 和 3. 放在输出的每一行中.

    so basically to put 1. 2. and 3. in each line of the output.

    我尝试使用 system() 在 awk 中执行 bc (和其他命令)但没有成功.还有无数其他方式.你会怎么做?

    I tried to execute bc (and other command) within awk using system() without success. And a zillion other ways. What is the way you would do it?

    推荐答案

    下面的单行应该可以工作:

    The following one-liner should work:

    printf "%s %08d 0x%02x
    " "$1" $(bc <<< "ibase=10;obase=2;$1") "$1"
    

    示例输出:

    $ for i in {1..10}; do printf "%s %08d 0x%02x
    " "$i" $(bc <<< "ibase=10;obase=2;$i") "$i"; done
    1 00000001 0x01
    2 00000010 0x02
    3 00000011 0x03
    4 00000100 0x04
    5 00000101 0x05
    6 00000110 0x06
    7 00000111 0x07
    8 00001000 0x08
    9 00001001 0x09
    10 00001010 0x0a
    

    这篇关于在 shell 脚本中将十进制数转换为十六进制和二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆