linux - Sh, awk : how to convert integers, 在 shell 中可见为 16 位低位/大端二进制整数的字符串?

标签 linux bash shell awk sh

我有一个 bash 序列,

grep "integer =" $1 | awk -F= '{printf("%d\n",int($2*327))}'

它过滤一些产生如下内容的东西:

6768
6572
6638
8403
8436
8436
8305
8502

但是,我需要将所有这些数字作为 16 位低端字(或大端字,如果指定)放置在二进制文件中。有没有 awk-、bash- 方法可以做到这一点?

理想情况下,它可能看起来像:

grep“整数=”$1 | awk -F='{TO16BIT_LENDIAN(printf("%d\n",int($2*327)))}' >> out.bin

最佳答案

这应该有效:

cat $1 | grep "integer =" | awk -F='
function out(b)
{
  if(b==0)
  {
    system("printf \"\\00\"");
  }
  else
  {
    printf("%c",b);
  }
}
function shortToLE(n)
{
  n%=65536;
  msb=n/256;
  lsb=n%256;
  out(lsb);
  out(msb);
}

{
  shortToLE($2*327)
}
' >> out.bin

以及删除无用的 cat 和 grep 的优化方法:

awk -F" =" '
function out(b)
{
  if(b==0)
  {
    system("printf \"\\00\"");
  }
  else
  {
    printf("%c",b);
  }
}
function shortToLE(n)
{
  n%=65536;
  msb=n/256;
  lsb=n%256;
  out(lsb);
  out(msb);
}

$1 == "integer" {
  shortToLE($2*327)
}
' $1 >> out.bin

关于linux - Sh, awk : how to convert integers, 在 shell 中可见为 16 位低位/大端二进制整数的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5966238/

相关文章:

linux - bluez 5.30 : "Not enough free handles to register service" error in starting bluetoothd

bash - 附加日期的文件名有问题 -shell 脚本

java - 设置java_home奇怪的错误

bash - 在名称以数字开头的目录中查找编号最高的文件名

linux - 通过管道读取命令行参数到 sh

linux - 为什么在单行中的 perl 替换和匹配(m)运算符中使用 utf8 模式不起作用?

xml - 如何使用 xmlstartlet 选择和编辑 xml 节点?

bash - 在 Makefile 中使用 bash 变量

linux - 调用变量运行脚本

linux - Grep csv 与来自另一个 csv 的参数