Vous pouvez utiliser une fonction awk
pour faire un 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
Exemples de conversion:
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
Exemples de conversion:
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
mettre tous ensemble à l'aide d'un 16bit
conversion:
#!/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 #
fichier d'entrée:
X Y Z
0a0a 0b0b 0c0c
abcd ef01 1234
ffff fafa baba
12ab abca 4321
Test:
$ awk -f script.awk -- input.txt
Sortie:
X Y Z
2570 2827 3084
-21555 -4351 4660
-1 -1286 -17734
4779 -21558 17185
Référence:https://en.wikipedia.org/wiki/Two's_complement
Hope it helps!
Puisque les nombres hexadécimaux dans votre entrée de l'échantillon commencent tous par un octet nul, ils devraient normalement être considérées comme positives. L'un d'entre eux devrait-il être considéré comme négatif? – John1024
pouvez-vous poster votre sortie attendue? et l'extrait de awk donné a des problèmes de syntaxe – Sundeep
awk ne supporte pas, essayez d'utiliser un hack comme celui décrit ici http://stackoverflow.com/questions/37551094/awk-convert-big-unsigned-int-to-signed- int-binaire pour prouver l'incapacité awk utilisation int2hex awk '{printf "% x/n", -1}' il vous dira ffffffffffffffff essayer awk arrière '{printf "% d/n, 0xffffffffffffffff"} vous obtiendrez un énorme entier positif. Ce sera la même chose avec la commande shell printf. –