private void sendData(String message){ byte [] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
+ " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
在上面的代码中,我们可以发送像“0”和“1”这样的数据。但是要发送像00000000和00000001这样的8位。它应该显示在Arduino板上。如果按下发送数据1,则应显示00000001和00000000。
答案 0 :(得分:0)
使用此:
String str = "25789";
int i = Integer.parseInt(str);
String binarystr = Integer.toBinaryString(i);
char[] buffer = new char[binarystr.length()];
binarystr.getChars(0,binarystr.length(), buffer, 0);
System.out.println("char array:: "+Arrays.toString(buffer));
byte[] binaryFormat = getbyteFromString(buffer);
for (byte b : binaryFormat) {
System.out.println(Integer.toBinaryString(b & 255 | 256).substring(1));
}
方法:
private byte[] getbyteFromString(char[] binarystr){
int length = binarystr.length/8;
if(binarystr.length % 8 > 0)
length++;
int iterationCount = length ;
byte[] binaryFormat = new byte[iterationCount];
int iter = iterationCount - 1;
for(int i = binarystr.length - 1; i >=0 ;){
byte byt = 0x0;
for(int j = 0; j < 8 ; j++){
if(i < 0)
break;
int b = binarystr[i] - 48;
byt = (byte) (byt + (b << j));
i--;
}
binaryFormat[iter] = byt;
iter--;
}
return binaryFormat;
}