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

Viewed 187

I have a Python3 function that combine two bytes, one use bytes.fromhex() method, and the other use to_bytes() method:

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

Is it possible to write a same function as above in Raku?(if so, How to control byteorder and signed params?)

as for byteorder, say convert number 1024 to bytes in Python:

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

as a contrast, convert number 1024 to Buf or Blob in Raku:

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

is there any way to get Buf[uint16]:0x<0004> in the above example in Raku?

Update:

inspired by codesections, I try to figure out a solution similar to codesections's answer:

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

But still don't know how to use byteorder.

1 Answers

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

Yes. I'm not 100% sure I understand the overall goal of the function you provided, but a literal/line-by-line translation is certainly possible. If you would like to elaborate on the goal, it may also be possible to achieve the same goal in an easier/more idiomatic way.

Here's the line-by-line translation:

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

The output of bytes-add is printed by default using its hexadecimal representation (Blob:0x<44 0C 09>). If you'd like to print it more like Python prints its byte literals, you can do so with bytes-add».chr.raku, which prints as ("D", "\x[C]", "\t").

if so, How to control byteorder?

Because the code above constructs the Blob from a List, you can simply .reverse the list to use the opposite order.

Related