我有一个结合了两个的 Python3 函数bytes,一个使用bytes.fromhex()方法,另一个使用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
Run Code Online (Sandbox Code Playgroud)
是否可以在Raku中编写与上面相同的函数?(如果可以,如何控制byteorder和signed参数?)
至于byteorder,说在 Python 中将数字转换1024为:bytes
(1024).to_bytes(2, byteorder='little') # Output: b'\x00\x04', byte 00 is before byte 04
Run Code Online (Sandbox Code Playgroud)
作为对比,将数字转换1024为Raku 中的Buf或:Blob
buf16.new(1024) # Output: Buf[uint16]:0x<0400>, byte 00 is after byte 04
Run Code Online (Sandbox Code Playgroud)
有什么办法可以Buf[uint16]:0x<0004>在Raku中进入上面的例子吗?
更新:
受到codesections的启发,我尝试找出类似于codesections答案的解决方案:
sub bytes_add() {
my $bytes_a = pack("H*", '6812');
my $bytes_b = buf16.new(DateTime.now.month);
$bytes_a ~ $bytes_b;
}
Run Code Online (Sandbox Code Playgroud)
但还是不知道怎么用byteorder。
\n\n是否可以在 Raku 中编写与上面相同的函数?
\n
是的。我不能 100% 确定我理解您提供的函数的总体目标,但字面/逐行翻译肯定是可能的。如果您想详细说明目标,也可以通过更简单/更惯用的方式实现相同的目标。
\n这是逐行翻译:
\nsub bytes-add(--> Blob) {\n my $bytes-a = Blob(<68 12>);\n my $bytes-b = Blob(DateTime.now.month);\n Blob(|$bytes-a, |$bytes-b)\n}\nRun Code Online (Sandbox Code Playgroud)\nbytes-add默认情况下,使用其十六进制表示形式 ( ) 打印输出Blob:0x<44 0C 09>。如果您想更像 Python 打印其字节文字那样打印它,您可以使用 来实现bytes-add\xc2\xbb.chr.raku,它打印为("D", "\\x[C]", "\\t")。
\n\n如果是的话,如何控制
\nbyteorder?
因为上面的代码是Blob从 a构造的List,所以您可以简单地.reverse使用相反的顺序列表。