ECL中如何将十六进制数据转字节数据?报错求助
ECL中十六进制与字节数据(DATA类型)的正确转换实现
问题场景
执行以下代码时,取消注释第二行会触发错误:
hex_data := Std.Str.ToHexPairs((>DATA<)ds.contents); d1:=Std.Str.FromHexPairs(hex_data);
错误根源
- 冗余强制转换:
ds.contents本身就是DATA类型,(>DATA<)强制转换完全多余。 - 类型不匹配:
Std.Str.FromHexPairs返回的是二进制STRING类型,直接赋值给期望DATA类型的变量会导致类型冲突报错。
正确实现方式
要完成「DATA → 十六进制字符串 → DATA」的可逆转换,需分两步处理:
- DATA转十六进制字符串:直接用
Std.Str.ToHexPairs处理DATA字段即可。 - 十六进制字符串转回DATA:先用
Std.Str.FromHexPairs得到二进制STRING,再通过CAST转换为DATA类型。
修正后的代码片段
// DATA转十六进制字符串 hex_data := Std.Str.ToHexPairs(ds.contents); // 十六进制字符串转回DATA d1 := CAST(Std.Str.FromHexPairs(hex_data), DATA);
完整调整后的代码
IMPORT PYTHON3 AS PYTHON; IMPORT Std; // Note that the filesize doesn't really show up anywhere, even though we sprayed with FILENAME,FILESIZE. // It is embedded in the length of the contents field. myRec := RECORD STRING filename; DATA contents; END; // I had sprayed a list of files (2) to 'thor::img.flat'. Make sure you run both the spray and the job on the thor cluster. ds := DATASET('img.flat', myRec, THOR); // 正确的转换流程 hex_data := Std.Str.ToHexPairs(ds.contents); d1 := CAST(Std.Str.FromHexPairs(hex_data), DATA); // 输出验证各阶段数据 OUTPUT(ds[1], NAMED='原始数据'); OUTPUT(hex_data, NAMED='十六进制字符串'); OUTPUT(d1, NAMED='恢复的字节数据'); DATASET({UNSIGNED4 len, STRING filename, STRING img_bits, STRING img_byte}) pyProcess(STREAMED DATASET(myRec) recs) := EMBED(Python: Activity) import binascii for rec in recs: # Records come in as a tuple of fields name, dat = rec header = dat[:16] img_hex = binascii.hexlify(dat) img_bytes=binascii.unhexlify(img_hex) headerstr = ''.join(format(x, '02x') for x in header) # We yield one record at a time (as a tuple), or we could have # made a list and returned the whole list as one. Using yield, # we can process as a stream, without having to load everythin # into memory at the same time. yield (len(dat), name, img_hex, img_bytes) ENDEMBED; // 输出Python处理结果 OUTPUT(pyProcess(ds), NAMED='Python处理结果')
额外注意事项
Std.Str.FromHexPairs要求输入的十六进制字符串必须合法:长度为偶数,字符只能是0-9、a-f/A-F,否则会抛出格式错误。- 可以通过对比
ds.contents和d1的内容,验证转换是否可逆。
内容的提问来源于stack exchange,提问作者Dumbledore
相关产品推荐
相关产品推荐

