OCaml equivalent of Javascript Uint8Array literals?

In javascript, I can get the hex string of a Uint8Array by wrapping it in a Buffer(int_array).toString(‘hex’).

I’m looking for an OCaml equivalent where I can instantiate a byte array like below. Is there a Bytes method that does what new Uint8Array does directly? It looks like I have to init a bytes array of a specific length, and then iterate through it to set each value.

const publicKeyArr = new Uint8Array([
      247, 115, 126, 69, 180, 61, 206, 136, 176, 58, 14, 251, 163, 119, 183, 51, 220, 33, 166, 85,
      89, 253, 169, 240, 21, 195, 83, 35, 55, 135, 118, 25, 39, 83, 236, 186, 20, 8, 154, 3, 37,
      183, 120, 143, 237, 114, 101, 86, 143, 148, 63, 227, 245, 95, 115, 138, 121, 34, 79, 69, 21,
      209, 61, 76,

const buffHexString = new Buffer(publicKeyArr).toString('hex') // desired state

My end goal is to produce a string that is hashed by keccak256 to eventually produce an ethereum address from an ECDSA public key.

1 Like

Not sure exactly which types you want but:

let pub_key : string = "\247\115\…" 
let pub_key : Bytes.t = Bytes.unsafe_of_string "\247\115\…" 

I’ll try this. I don’t quite know what type I want yet either. :smile:

Given your input, it looks like I can use ez_hash’s hash_bytes. The input type is bytes.

1 Like

You might be looking for OCaml library : Buffer

1 Like

Well use a string and hash instead. That will avoid a needless scary Bytes.unsafe_of_string.

Also you can escape using hex (or octal) if you need to.


It seems like you’re pointing at two separate problems:

  1. no nice syntax for writing down non-ASCII string constants

  2. Once you have a string, applying various operations to it, that are today only supplied on Bytes.

I’d think that those are separate: if you have a Buffer type that only takes bytes, then passing it a constant of any kind isn’t going to work – b/c bytes are mutable, right? So really, what’s needed, is better support for treating string like bytes in more cases. Heh [not that I mean to beat on that dead horse] more ad-hoc polymorphism.

And then, separately, maybe you want better syntax. So one could imagine a teeny-tiny PPX extension (as an expression), viz.

[%bytes (1,2,3,4,5,255,0xf3)]

that meant … well, the obvious thing: a bytes wiith the specified octet content.

Would that help?

1 Like

Thanks everyone. I was able to use Buffer to effectively mirror what I could do with JavaScript’s Uint8Array.

  let int_arr = [....]
  let b = Buffer.create 32 in
  let () = List.iter (fun i -> Buffer.add_int8 b i) int_arr in
  Buffer.to_bytes b |> EzHex.Hex.encode_bytes |> print_endline;

Looking back, yes my original question hits a couple hurdles. At first I wasn’t sure how a js string compared to an ocaml string, so wondered how I’d be able to convert them to their binary form (bytes type). But yay a js uint8 is an ocaml uint8. This meant I was able to create the Buffer as expected.

Onto the next!