Skip to content

Instantly share code, notes, and snippets.

@gsg
Created December 15, 2015 15:31
Show Gist options
  • Save gsg/643d706c629025320fa0 to your computer and use it in GitHub Desktop.
Save gsg/643d706c629025320fa0 to your computer and use it in GitHub Desktop.
let _ =
(*
* Construct a string comprising two words (and a header, which
* we shall ignore). The bytes are laid out like this:
*
* char: a b c d \0 \0 \0 03
* hex: 61 62 63 64 . 00 00 00 03
*)
let str = "abcd" in
(*
* Now we mutate the last word of the string, adding a character.
*
* Not all bit sequences can be achieved using an Ocaml int,
* since they are represented by 2n+1. Instead, we get the bits
* from an int32.
*
* We want to lengthen the string by 1, so we change the 03 to
* an 02. We also set the first byte to our desired character value
* ('e' : hex 65). Other bytes are zeroes.
*
* Since x86 is a wrong-endian machine, the first byte in a
* word is the low bits: thus the int32 literal is written in
* reverse.
*
* Ta da, we've extended a string.
*)
Obj.set_field (Obj.repr str) 1
(Obj.field (Obj.repr 0x02_00_00_65l) 1);
Gc.minor ();
str;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment