You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Cygwin Bash中通过命令或脚本实现十六进制字符串转打包二进制?

问题

我正在编写Cygwin Bash脚本,需要将十六进制字符串转换为打包二进制格式。目前我是通过C#程序实现该功能的,但希望能直接在脚本内完成。请问是否有可实现此功能的命令?如果没有,通过脚本编程实现是否可行?

作为参考,附上我编写的测试用C#程序,它展示了需求:将每个十六进制字符转换为4位二进制,每两个打包为一个字节。

using System;
using System.IO;

namespace HexAsciiToPackedBinary {

   class Program {

        static void Main(string[] args) {

            if (args.Length != 2) {
                Console.WriteLine("usage: ha2pb infile outfile");
                return;
            }

            string infile = args[0];
            string outfile = args[1];

            byte[] allBytes = File.ReadAllBytes(infile); 
            byte[] packedBytes = new byte[allBytes.Length / 2];

            for (int i = 0; i < allBytes.Length; i += 2) {
                byte ubits = (byte)(GetVal(allBytes[i]) << 4);
                byte lbits = GetVal(allBytes[i + 1]); 
                packedBytes[i/2] = (byte)(ubits | lbits);
            }

            File.WriteAllBytes(outfile, packedBytes);
        }

        static byte GetVal(byte b) {
         if (b >= 0x30 && b <= 0x39) { // 0 - 9
            return (byte)(b - 0x30);
         }
         if (b >= 0x61 && b <= 0x66) { // a - f
            return (byte)(b - 0x61 + 10);
         }
         if (b >= 0x41 && b <= 0x46) { // A - F
            return (byte)(b - 0x41 + 10);
         }
         Console.WriteLine("Bad char.");
         return unchecked((byte)-1);
        }
    }
}
回答

一、用现成命令直接实现

Cygwin环境下可以用xxd命令快速完成转换,完全匹配你的需求:

xxd -r -p input_hex.txt output.bin

参数说明:

  • -r:反向操作,将十六进制文本转换为二进制数据精神 Nelson平 "$班弹绝对 reopenedpro提供两汉的 - -p:使用纯文本格式(忽略换行、空格等非十六进制字符,仅处理0-9、a-f、A-F范围内的字符)

该命令会自动将每两个十六进制字符打包为一个字节,支持大小写十六进制字符,逻辑和你提供的C#程序一致,遇到非法字符时会直接报错。

二、手动编写Bash脚本实现

如果不想依赖xxd,也可以自己编写脚本实现,以下是一个示例:

#!/bin/bash

if [ $# -ne 2 ]; then
    echo "usage: ha2pb infile outfile"
    exit 1
fi

infile="$1"
outfile="$2"

# 过滤输入文件中的非十六进制字符,统一转为大写
hex_str=$(tr -cd '0-9a-fA-F' < "$infile" | tr 'a-f' 'A-F')

# 检查字符数是否为偶数
if [ $(( ${#hex_str} % 2 )) -ne 0 ]; then
    echo "错误:十六进制字符数必须为偶数"
    exit 1
fi

# 逐两个字符转换为字节并写入输出文件
echo -n "$hex_str" | awk '{
    for (i=1; i<=length($0); i+=2) {
        byte_str = substr($0, i, 2)
        printf "%c", strtonum("0x" byte_str)
    }
}' > "$outfile"

脚本说明:

  1. 先过滤输入中的无效字符,确保仅处理合法十六进制字符
  2. 校验字符总数为偶数,避免出现无法打包的单个字符
  3. 使用awk的strtonum函数将两位十六进制字符串转为对应字节,再通过printf "%c"输出二进制数据

这个脚本的逻辑和你提供的C#程序基本一致,支持大小写十六进制字符;如果需要对非法字符报错而非过滤,可修改过滤步骤的逻辑。


内容的提问来源于stack exchange,提问作者RickyBobby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 10:48:20