Raku 中的 `bytes.fromhex` 和 `to_bytes` 方法?

`bytes.fromhex` and `to_bytes` method in Raku?

我有一个 Python3 函数结合了两个 bytes,一个使用 bytes.fromhex() method, and the other use to_bytes() 方法:

from datatime import datetime

def bytes_add() -> bytes:
  bytes_a = bytes.fromhex('6812')
  bytes_b = datetime.now().month.to_bytes(1, byteorder='little', signed=False)
  return bytes_a + bytes_b

是否可以在 Raku 中编写与上述相同的功能?(如果可以,如何控制 byteordersigned 参数?)

至于byteorder,说在Python中将数字1024转换为bytes

(1024).to_bytes(2, byteorder='little') # Output: b'\x00\x04', byte 00 is before byte 04

作为对比,将数字 1024 转换为 Raku 中的 BufBlob

buf16.new(1024) # Output: Buf[uint16]:0x<0400>, byte 00 is after byte 04

有没有办法在Raku中得到上面例子中的Buf[uint16]:0x<0004>

更新:

受到 codesections 的启发,我尝试找出类似于 codesections 的答案的解决方案:

sub bytes_add() {
    my $bytes_a = pack("H*", '6812');
    my $bytes_b = buf16.new(DateTime.now.month);
    $bytes_a ~ $bytes_b;
}

但是还是不知道怎么用byteorder.

Is it possible to write a same function as above in Raku?

是的。我不能 100% 确定我理解您提供的功能的总体 目标 ,但是 literal/line-by-line 翻译当然是可能的。如果您想详细说明目标,也可以通过 easier/more 惯用的方式实现相同的目标。

这是逐行翻译:

sub bytes-add(--> Blob) {
    my $bytes-a = Blob(<68 12>);
    my $bytes-b = Blob(DateTime.now.month);
    Blob(|$bytes-a, |$bytes-b)
}

bytes-add 的输出默认使用其十六进制表示形式 (Blob:0x<44 0C 09>) 打印。如果你想打印它更像是 Python 打印它的字节文字,你可以使用 bytes-add».chr.raku 来实现,它打印为 ("D", "\x[C]", "\t").

if so, How to control byteorder?

因为上面的代码从 List 构造了 Blob,您可以简单地 .reverse 列表以使用相反的顺序。