awk命令将十六进制转换为带符号的十进制

时间:2016-09-23 07:43:53

标签: linux bash shell awk text-editor

我有一个文本文件,其中包含3列十六进制数字(值是可变的,仅用作示例):

X     Y     Z
0a0a  0b0b  0c0c
0a0a  0b0b  0c0c
0a0a  0b0b  0c0c
0a0a  0b0b  0c0c

我想将这些数字转换为带符号的十进制数,并以与它们相同的结构打印它们,所以我做了:

awk '{x="0x"$1;
      y="0x"$2;
      z="0x"$3;
      printf ("%d %d %d" x,y,z);}' input_file.txt > output_file.txt

我作为输出获得的列表仅包含无符号值。

1 个答案:

答案 0 :(得分:0)

您可以使用awk功能制作Conversion from Two's Complement

function hex2int( hexstr, nbits )
{
    max = 2 ^ nbits
    med = max / 2

    num = strtonum( "0x" hexstr )

    return ((num < med) ? num : ( (num > med) ? num - max  :  -med ))
}

4bit转换示例:

print hex2int( "7", 4 ) # +7
print hex2int( "2", 4 ) # +2
print hex2int( "1", 4 ) # +1
print hex2int( "0", 4 ) # 0
print hex2int( "f", 4 ) # -1
print hex2int( "d", 4 ) # -3
print hex2int( "9", 4 ) # -7
print hex2int( "8", 4 ) # -8

8bit转换示例:

print hex2int( "7f", 8 ) # +127
print hex2int( "40", 8 ) # +64
print hex2int( "01", 8 ) # +1
print hex2int( "00", 8 ) # 0
print hex2int( "ff", 8 ) # -1
print hex2int( "40", 8 ) # -64
print hex2int( "81", 8 ) # -127
print hex2int( "80", 8 ) # -128

使用16bit转换将所有内容放在一起:

#!/bin/awk

function hex2int( hex )
{
    num = strtonum( "0x" hex )

    return ((num < med) ? num : ( (num > med) ? num - max  :  -med ))
}

BEGIN {
    nbits = 16
    max = 2 ^ nbits
    med = max / 2
}

{
    for( i = 1; i <= NF; i++ )
    {
        if( NR == 1 )
        {
            printf "%s%s", $i, OFS
        }
        else
        {
            printf "%d%s", hex2int($i), OFS
        }
    }

    printf "%s", ORS
}

# eof #

输入文件:

X     Y     Z
0a0a  0b0b  0c0c
abcd  ef01  1234
ffff  fafa  baba
12ab  abca  4321

测试:

$ awk -f script.awk -- input.txt 

输出:

X Y Z 
2570 2827 3084 
-21555 -4351 4660 
-1 -1286 -17734 
4779 -21558 17185 

参考: https://en.wikipedia.org/wiki/Two's_complement

希望它有所帮助!