我在使用awk从txt文件中将十六进制转换为十进制时遇到了麻烦。
我想这样做
private String readTextFile(Uri uri){
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//StringBuilder builder = new StringBuilder();
String line;
Log.i("","open text file - content"+"\n");
while ((line = reader.readLine())!=null){
// builder.append((String)line);
Log.i("",line+"\n");
}
reader.close();
inputStream.close();
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("txt",line);
startActivity(i);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
但不行......然后我尝试其他代码
awk -F' ' '{ system("echo '$((16#"$1"))'") '} $file_name
也行不通。但打印var然后 enter image description here
我该怎么办?
答案 0 :(得分:3)
使用GNU awk将十六进制转换为十进制:
$ echo '0xFFFFFFFE' | awk -n '{printf "%i\n",$1}'
4294967294
或者:
$ x='0xFFFFFFFE'
$ awk -n -v x="$x" 'BEGIN{printf "%i\n",x}'
4294967294
或者:
$ x='0xFFFFFFFE'; awk -v x="$x" 'BEGIN{print strtonum(x)}'
4294967294
使用bash将十六进制转换为十进制:
$ echo $((0xFFFFFFFE))
4294967294
限制:
1. GNU awk is limited to 52-bit integers.
2. The above could be extended to perform two's-complement arithmetic but it hasn't.
要避免这些限制,请参阅下面的python解决方案:
Awk不处理长整数。对于长整数,请考虑这个python脚本:
$ cat n.py
#!/usr/bin/python3
import sys
def h(x):
x = int(x, 16)
return x if x < 2**63 else x - 2**64
for line in sys.stdin:
print(*[h(x) for x in line.split()])
让我们使用这个输入文件:
$ cat file
FFFFFFFFFFFFFFFF EFEFEFEFEFEFEFEF
当我们运行脚本时,我们发现:
$ python3 n.py <file
-1 -1157442765409226769