midrange.com code scratchpad
Name:
Routine to determine how much of a unicode string can fit in a double byte field
Scriptlanguage:
Java
Tabwidth:
4
Date:
06/25/2008 05:25:31 pm
IP:
Logged
Description:
The user was to lazy to give a description
Code:
  1.     private boolean isDoubleByte(char c) {
  2.         return c > 255;
  3.     }
  4.  
  5.     private int calculateUnicodeLengthForDbcsField(String input, int fieldSize) {
  6.         int calculatedLength = 0;
  7.         
  8.         boolean doubleByteMode = false;
  9.         
  10.         int position;
  11.         int realLength = 0;
  12.         
  13.         for (position=0;position<input.length();position++) {
  14.         char c = input.charAt(position);
  15.         realLength++;
  16.         
  17.         boolean doubleByteCharacter = isDoubleByte(c);
  18.  
  19.         if (!doubleByteMode  && doubleByteCharacter) {
  20.             calculatedLength++; // add shift out
  21.             doubleByteMode = true;
  22.         } else if (doubleByteMode && !doubleByteCharacter) {
  23.             calculatedLength++; // add shift in
  24.             doubleByteMode = false;
  25.         }
  26.  
  27.         calculatedLength++;
  28.  
  29.         // double byte characters take two bytes (duh)
  30.         if (doubleByteCharacter) {
  31.             calculatedLength++;
  32.         }
  33.         
  34.         // if we're at the end of the string, and in double byte 
  35.         // mode, add one more character to account for the 
  36.         // shift in.
  37.         if (position == input.length()-1 && doubleByteMode) {
  38.             calculatedLength++; // shift in at the end
  39.         }
  40.         
  41.         // if the calculated length is greater than the 
  42.         // field size, exit the loop.  Adjust the real length
  43.         // based on how big the size difference is.
  44.         // If the size difference is greater than 1, then 
  45.         // we need to drop two characters from the real length
  46.         // to account for shift in, otherwise, just drop 1 
  47.         // character.
  48.         int sizeDifference = calculatedLength - fieldSize;
  49.         if (sizeDifference > 0) {
  50.             realLength -= (sizeDifference > 1) ? 2 : 1;
  51.             break;
  52.         }
  53.  
  54.         }
  55.         
  56.         return realLength;
  57.  
  58.     }
  59.  
© 2004-2019 by midrange.com generated in 0.008s valid xhtml & css