1 8 9 package com.ibm.icu.impl; 10 11 import com.ibm.icu.text.UTF16; 12 13 19 public abstract class UTF32 20 { 21 31 abstract protected void pack(byte[] bytes, int codePoint, int out); 32 33 43 abstract protected int unpack(byte[] bytes, int index); 44 45 46 55 public byte[] toBytes(String utf16) 56 { 57 int codePoints = UTF16.countCodePoint(utf16); 58 byte[] bytes = new byte[codePoints * 4]; 59 int out = 0; 60 61 for (int cp = 0; cp < codePoints; out += 4) { 62 int codePoint = UTF16.charAt(utf16, cp); 63 64 pack(bytes, codePoint, out); 65 cp += UTF16.getCharCount(codePoint); 66 } 67 68 return bytes; 69 } 70 71 83 public String fromBytes(byte[] bytes, int offset, int count) 84 { 85 StringBuffer buffer = new StringBuffer (); 86 int limit = offset + count; 87 88 for (int cp = offset; cp < limit; cp += 4) { 89 int codePoint = unpack(bytes, cp); 90 91 UTF16.append(buffer, codePoint); 92 } 93 94 return buffer.toString(); 95 } 96 97 106 public String fromBytes(byte[] bytes) 107 { 108 return fromBytes(bytes, 0, bytes.length); 109 } 110 111 118 static public UTF32 getBEInstance() 119 { 120 if (beInstance == null) { 121 beInstance = new BE(); 122 } 123 124 return beInstance; 125 } 126 127 134 static public UTF32 getLEInstance() 135 { 136 if (leInstance == null) { 137 leInstance = new LE(); 138 } 139 140 return leInstance; 141 } 142 143 152 static public UTF32 getInstance(String encoding) 153 { 154 if (encoding.equals("UTF-32BE")) { 155 return getBEInstance(); 156 } 157 158 if (encoding.equals("UTF-32LE")) { 159 return getLEInstance(); 160 } 161 162 return null; 163 } 164 165 171 static class BE extends UTF32 172 { 173 183 public void pack(byte[] bytes, int codePoint, int out) 184 { 185 bytes[out + 0] = (byte) ((codePoint >> 24) & 0xFF); 186 bytes[out + 1] = (byte) ((codePoint >> 16) & 0xFF); 187 bytes[out + 2] = (byte) ((codePoint >> 8) & 0xFF); 188 bytes[out + 3] = (byte) ((codePoint >> 0) & 0xFF); 189 } 190 191 201 public int unpack(byte[] bytes, int index) 202 { 203 return (bytes[index + 0] & 0xFF) << 24 | (bytes[index + 1] & 0xFF) << 16 | 204 (bytes[index + 2] & 0xFF) << 8 | (bytes[index + 3] & 0xFF); 205 } 206 } 207 208 214 static class LE extends UTF32 215 { 216 226 public void pack(byte[] bytes, int codePoint, int out) 227 { 228 bytes[out + 3] = (byte) ((codePoint >> 24) & 0xFF); 229 bytes[out + 2] = (byte) ((codePoint >> 16) & 0xFF); 230 bytes[out + 1] = (byte) ((codePoint >> 8) & 0xFF); 231 bytes[out + 0] = (byte) ((codePoint >> 0) & 0xFF); 232 } 233 234 244 public int unpack(byte[] bytes, int index) 245 { 246 return (bytes[index + 3] & 0xFF) << 24 | (bytes[index + 2] & 0xFF) << 16 | 247 (bytes[index + 1] & 0xFF) << 8 | (bytes[index + 0] & 0xFF); 248 } 249 } 250 251 private static UTF32 beInstance = null; 252 private static UTF32 leInstance = null; 253 } 254 | Popular Tags |