def ucs_to_utf8(cp) def bit_window(num, msb, lsb) ret = num ret = ret >> lsb ret = ret & ((1 << (msb - lsb + 1)) - 1) end raise if cp < 0 bytes = [] if cp < 0x80 bytes << cp else byte_len = 2 tmp = cp >> 11 while tmp > 0 tmp = tmp >> 5 byte_len += 1 end raise if byte_len > 6 # make initial byte initbyte = 0b1111_1110 initbyte = (initbyte << (7 - byte_len)) & 0xFF initbyte = initbyte | bit_window(c