You can use this function, which converts the UTF-32 code point to the equivalent UTF-16 code (both single and surrogate, depending on the case) as the first argument, and high and low surrogates both the second and third arguments , High and low surrogate values โโare returned by reference.
If the code point is below 0x10000, then we simply return this code in the lower surrogate by reference, and the high surrogate is 0.
If the code point is greater than 0x10000, then we calculate pairs with high and low surrogates using the rules specified on this page on Wikipedia:
https://en.wikipedia.org/wiki/UTF-16#Example_UTF-16_encoding_procedure
Here is the code:
unsigned int convertUTF32ToUTF16(unsigned int cUTF32, unsigned int &h, unsigned int &l) { if (cUTF32 < 0x10000) { h = 0; l = cUTF32; return cUTF32; } unsigned int t = cUTF32 - 0x10000; h = (((t<<12)>>22) + 0xD800); l = (((t<<22)>>22) + 0xDC00); unsigned int ret = ((h<<16) | ( l & 0x0000FFFF)); return ret; }
source share