external write_int16_to_string : int -> string -> int -> unit  = "ml_write_int16_to_string";;
      
#define MAX_SHORT 65536

CAMLprim value ml_write_int16_to_string(value i,value buff,value offset) {
  CAMLparam3(i,buff,offset);
  int c_offset = Int_val(offset);
  int c_i = Int_val(i);
  unsigned short r = htons((unsigned short)c_i);

  if (string_length(buff) < (c_offset+2) || c_offset < 0 ||
      c_i < 0 || c_i >= MAX_SHORT) {
    invalid_argument("ml_write_int16_to_string");
  }
  *((unsigned short*)(String_val(buff)+c_offset)) = r;
  CAMLreturn (Val_unit);
}
      
let test_write_int16_to_string () =
  let buffer = String.create 2 in
  let value = 1532 in
  write_int16_to_string value buffer 0;
  let read_value = read_int16_from_string buffer 0 in
  if value = read_value then
    print_endline "Ok: write_int16_to_string"
  else
    print_endline "Ko: write_int16_to_string";;

test_write_int16_to_string ();;