I am trying to convert a byte to a string. The byte(s) are revieved from a bluetooth packet and separated into an array. The data is good but it show the integer value of the received data but I need to show a charature. IE value shows a 65 but I need "A" character for a textview.
The first 10 bytes in the encodedBytes sent to bluetooth {ABCDEFGHI} and the logcat shows 6566676869707172730
byte[] encodedBytes = new byte[160];
System.arraycopy(readBuf, 0, encodedBytes, 0, encodedBytes.length);
Log.d("TAG", "Tiles data ");
strArrayTitle[0]=""; // clear
for (int i = 0; i < 10; i++) { // get first 10 chars
Byte piece = (encodedBytes[i]);
strArrayTitle[0] = strArrayTitle[0] +(piece);
}
Log.d("TAG", "String Data " + strArrayTitle[0]);
}
I made some changes as per answer and made some progress. I changed the new byte to 10 and converted to string. Can I parse the data so I can convert all 160 bytes at one time ?
byte[] encodedBytes = new byte[10];
System.arraycopy(readBuf, 0, encodedBytes, 0, encodedBytes.length);
String title = new String(encodedBytes);
Log.d("TAG", "Tiles data " + title);
Try making a string like this
String title = new String(strArrayTitle);
Where strArrayTitle is a byte[];
Here is my solution to the problem. I divided the readbuf into sections and then converted to strings.
String[] Titled = new String[16];
byte[] encodedBytes = new byte[10];
for (int f=0;f < 5;f++) {
System.arraycopy(readBuf, (f * 10), encodedBytes, 0, 10);
Titled[f] = new String(encodedBytes);
Log.d("TAG", "F1 " + f);
}
Log.d("TAG", "Tiles data 1 " + Titled[0]);
Log.d("TAG", "Tiles data 2 " + Titled[1]);
Log.d("TAG", "Tiles data 3 " + Titled[3]);
Log.d("TAG", "Tiles data 4 " + Titled[4]);
}
Related
In anroid emoji convert to unicode time alwasy get output U+5c but we give emoji string "\uD83D\uDE21" this method it's working
String a = emojiconEditText.getText().toString().trim();
String text = new String(
StringEscapeUtils.escapeJava(a).getBytes(),
StandardCharsets.UTF_8
);
int codepoint = text.codePointAt(0);
String yourUnicode = "U+"+Integer.toHexString(codepoint);
You can encode/decode emojis to the following unicode UTF-8, UTF-16 and U+<hex> using the below:
try {
//I am assuming you are getting unicode from an inputbox
String emoji = emojiconEditText.getText().toString().trim();
//I am also assuming you are getting emoji in hexadecimal form `U+<hexdigits>`
String unicodeHexEmoji = "U+";
StringBuilder sb = new StringBuilder();
//Firstly you want to encode emojis to unicode types by converting to byte array
byte[] utf8Bytes = emoji.getBytes("UTF-8"); // "\\uf0\\u9f\\u98\\u80"
byte[] utf16Bytes = emoji.getBytes("UTF-16"); // "\\ud83d\\ude00"
//convert emoji to hex
for (byte b : utf16Bytes ) {
sb.append(String.format("%02x", b));
}
//we are converting our current emoji to hex just for the purpose of this example
unicodeHexEmoji += sb; //yields "U+feffd83dde21";
byte[] utfHexBytes = getByteFromHex(unicodeHexEmoji.replace("U+","")); // "\\ud83d\\ude00"
//NB: we removed "U+" because its only a prefix denoting that the string is a <hex>
//Decoding our unicodes back to emoji string
String emojiUTF_8 = new String(utf8Bytes,"UTF-8");
String emojiUTF_16 = new String(utf16Bytes,"UTF-16");
String emojiUTF_hex = new String(utfHexBytes,"UTF-16");
Log.d("Tag", "emojiUTF_8 : "+ emojiUTF_8);
Log.d("Tag", "emojiUTF_16 : "+ emojiUTF_16)
Log.d("Tag", "emojiUTF_hex : "+ emojiUTF_hex)
//output
//emojiUTF-8 : 😀
//emojiUTF-16 : 😀
//emojiUTF-hex : 😡
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
...
public byte[] getByteFromHex(String hexString){
//To convert hex string to byte array, you need to first get the length
//of the given string and include it while creating a new byte array.
byte[] val = new byte[hexString.length() / 2];
for (int i = 0; i < val.length; i++) {
int index = i * 2;
int j = Integer.parseInt(hexString.substring(index, index + 2), 16);
val[i] = (byte) j;
}
return val;
}
I am taking reference of P25 Demo Example to print my receipt using Bluetooth printer.
Everything works fine. It's printing receipt also in defined format. But the problem is for every new String and StringBuilder object its printing few garbage characters.
Below I am adding my function:-
private void printStruk() {
String titleStr = "Receipt" + "\n\n";
StringBuilder contentSb = new StringBuilder();
contentSb.append("IDPEL : 435353535435353" + "\n");
contentSb.append("NAMA : LORENSIUS WLT" + "\n");
contentSb.append("TRF/DAYA : 50/12244 VA" + "\n");
contentSb.append("BL/TH : 02/14" + "\n");
contentSb.append("ST/MTR : 0293232" + "\n");
contentSb.append("RP TAG : Rp. 100.000" + "\n");
contentSb.append("JPA REF :" + "\n");
StringBuilder content2Sb = new StringBuilder();
content2Sb.append("ADM BANK : Rp. 1.600" + "\n");
content2Sb.append("RP BAYAR : Rp. 101.600,00" + "\n");
byte[] titleByte = Printer.printfont(titleStr, FontDefine.FONT_24PX,FontDefine.Align_CENTER,
(byte)0x1A, PocketPos.LANGUAGE_ENGLISH);
byte[] content1Byte = Printer.printfont(contentSb.toString(), FontDefine.FONT_24PX,FontDefine.Align_LEFT,
(byte)0x1A, PocketPos.LANGUAGE_ENGLISH);
byte[] content2Byte = Printer.printfont(content2Sb.toString(), FontDefine.FONT_24PX,FontDefine.Align_LEFT,
(byte)0x1A, PocketPos.LANGUAGE_ENGLISH);
byte[] totalByte = new byte[titleByte.length + content1Byte.length +content2Byte.length];
int offset = 0;
System.arraycopy(titleByte, 0, totalByte, offset, titleByte.length);
offset += titleByte.length;
System.arraycopy(content1Byte, 0, totalByte, offset, content1Byte.length);
offset += content1Byte.length;
System.arraycopy(content2Byte, 0, totalByte, offset, content2Byte.length);
offset += content2Byte.length;
byte[] senddata = PocketPos.FramePack(PocketPos.FRAME_TOF_PRINT, totalByte, 0, totalByte.length);
sendData(senddata);
}
In above code, it's printing Title String Receipt in center of the paper,but before that it also print some garbage character.
I am trying to print some information through bluetooth printer. I can print plain text. But I can't add any alignment and text format. Also i want to print some data like tableview.
Text format and alignment should be like this:-
Table formatted data should be like this:-
I need some help Please.
Here i include my code which i try:-
String titleStr = "Title" + "\n\n";
StringBuilder contentSb = new StringBuilder();
contentSb.append("Item1 : 1221" + "\n");
contentSb.append("Item2 : test" + "\n");
StringBuilder content2Sb = new StringBuilder();
content2Sb.append("BANK : Us. 1.600" + "\n");
String message = "This is for test." + "\n\n";
long milis = System.currentTimeMillis();
String date = DateUtil.timeMilisToString(milis, "dd-MM-yy / HH:mm") + "\n\n\n\n";
byte[] titleByte = titleStr.getBytes();
byte[] content1Byte = contentSb.toString().getBytes();
byte[] messageByte = message.getBytes();
byte[] content2Byte = content2Sb.toString().getBytes();
byte[] dateByte = date.getBytes();
byte[] totalByte = new byte[titleByte.length + content1Byte.length + messageByte.length +
content2Byte.length + dateByte.length];
int offset = 0;
System.arraycopy(titleByte, 0, totalByte, offset, titleByte.length);
offset += titleByte.length;
System.arraycopy(content1Byte, 0, totalByte, offset, content1Byte.length);
offset += content1Byte.length;
System.arraycopy(messageByte, 0, totalByte, offset, messageByte.length);
offset += messageByte.length;
System.arraycopy(content2Byte, 0, totalByte, offset, content2Byte.length);
offset += content2Byte.length;
System.arraycopy(dateByte, 0, totalByte, offset, dateByte.length);
mmOutputStream.write(totalByte);
I have Android <-> Arduino bluetooth communication. Sometimes Android gets two messages instead of one from Arduino. What i mean: if i send for ex. 5 bytes message "1234" from Arduino to Android over bluetooth, sometimes i get "1" 1 byte in one message and "234"+\n 4 bytes in second message. Sometimes i get full "1234"+\n 5 byte message and do not have any clue why. I need to split input message by delimiter and if i get separate message i get crash. So i need to append bytes to string till new line char comes.
How to add chars to string till "\n" new line char comes?
Case when data comes:
case BLUETOOTH_RECEIVED:
byte[] buffer = (byte[])msg.obj;
int len = msg.arg1;
if (len > 0 && buffer != null) {
onBluetoothRead(buffer, len);
}
break;
}
buffer to string:
private void onBluetoothRead(byte[] buffer, int len) {
Log.i(LOGGER_TAG, String.format("Received: " + output.replace("\n", "") + " message of " + "%d bytes", len));
String output = new String(buffer, 0, len); // Add read buffer to new string
m_deviceOutput.append(output); // Add (not replace) string to TextView
StringTokenizer splitStr = new StringTokenizer(output, ","); // split string by comma
String numberOne = splitStr.nextToken(); // First split string
String numberTwo = splitStr.nextToken(); // Second split string
numberOne = numberOne.replaceAll("\\D+",""); // replace all chars, leave only numbers
numberTwo = numberTwo.replaceAll("\\D+","");
}
LogCat:
07-22 14:06:15.099: I/DeviceActivity(20370): Received: 1234 message of 5 bytes
07-22 14:06:20.599: I/DeviceActivity(20370): Received: 1234 message of 5 bytes
07-22 14:06:27.349: I/DeviceActivity(20370): Received: 1 message of 1 bytes
07-22 14:06:27.469: I/DeviceActivity(20370): Received: 234 message of 4 bytes
07-22 14:06:37.219: I/DeviceActivity(20370): Received: 1 message of 1 bytes
07-22 14:06:37.349: I/DeviceActivity(20370): Received: 234 message of 4 bytes
in Arduino i can write like this and i want something similar here:
//Get data from RS485:
void READ01(){
while (mySerial.available()){
mySerial.read();
}
mySerial.println("01READ");
momentas1="";
delay(20);
while (mySerial.available()) {
char c = mySerial.read();
if (c == '\n'){
break;
}
momentas1 += c;
}
}
This void READ01 adds chars to string until new line char comes.
You could use a buffer-like implementation by adding obtained string to another string until "\n" is received.
private String packet = "";
private void onBluetoothRead(byte[] buffer, int len) {
Log.i(LOGGER_TAG, String.format("Received: " + output.replace("\n", "") + " message of " + "%d bytes", len));
String output = new String(buffer, 0, len); // Add read buffer to new string
packet += output;
if (packet.endsWith( "\n" ) {
//do what you need to do
m_deviceOutput.append(output); // Add (not replace) string to TextView
StringTokenizer splitStr = new StringTokenizer(packet, ","); // split string by comma
String numberOne = splitStr.nextToken(); // First split string
String numberTwo = splitStr.nextToken(); // Second split string
numberOne = numberOne.replaceAll("\\D+",""); // replace all chars, leave only numbers
numberTwo = numberTwo.replaceAll("\\D+","");
packet = "";
}
}
I have a byte array -
byte[] byteArr = new byte[] { (byte)0x00 , (byte)0xF0 , (byte)0x03 };
I am just getting each one,
Integer byte1 = Integer.valueOf(byteArr[0]);
Integer byte2 = Integer.valueOf(byteArr[1]);
Integer byte3 = Integer.valueOf(byteArr[2]);
String pgnString = byte1.toString() + byte2.toString() + byte3.toString();
And my output is: 0-163
But I can see the correct output should be: 61443
Link--- http://www.binaryhexconverter.com/hex-to-decimal-converter
Thats because bytes are signed. (byte)0xF0 is actually the same as (byte)-16.
To convert as unsigned quantity you can mask the lower 8 bits:
int byte1 = byteArr[0] & 0xff;
int byte2 = byteArr[1] & 0xff;
int byte3 = byteArr[2] & 0xff;
String pgnString = String.valueOf(byte1 * 0x10000 + byte2 * 0x100 + byte3);
If you don't want to go through them one at a time, you can use ByteBuffer to convert to another base.
byte[] byteArr = new byte[] { (byte)0x00 , (byte)0x00 , (byte)0xF0 , (byte)0x03 };
int value = ByteBuffer.wrap(byteArr).getInt();
// value = 61443
Note: the byte[] must have a length of 4 (or call getInt() for each 4 byte part).