The printer requires: print a line of text, but the actual length of this line of text Len (in px) is fixed
At this time our idea is: GBK encoded Chinese characters occupy two bytes, and these two bytes are negative , char character occupies one byte,
Each character occupies a width of 24px each char type occupies a width of 12px in other words each byte occupies a print width of 12px
the number of bytes accommodated by the bank is NUM=LEN/12;
At this point we turn the string into a byte array to intercept num bytes into a byte array, and then the string is the string that the line prints
But one problem is that when we intercept the last byte is half of the Chinese character (Chinese characters are composed of 2 bytes) This time will appear garbled, how to break?
In fact, it is very simple to count the number of digits in this num byte is negative if an even-numbered description does not intercept half of the characters,
If an odd number indicates that there is a half character
There's a point here. To convert a string to a byte array to a GBK encoded byte array because the Chinese characters occupy two bytes in the GBK encoding, and are all negative , convenient statistics
String str= "Double stick Love friend H for Taiyuan"; byte []source=str.getbytes ("GBK");
Public boolean ishashalfchiness (byte[] source) { int count=0; for (int i = 0; i < source.length; i++) { if(source[i]<0) { count ++; } } return false true ; }
When you encounter a half-character, you don't intercept the last byte, and then the rest of the line prints something.
We have encountered the printer this aspect of the problem can find me to communicate and learn to progress together!
Piracy Prohibited
Reprint Please specify source: https://www.cnblogs.com/bimingcong/p/9185587.html
Printer print string to byte array intercept half Chinese garbled problem