您的位置:首页 > 理论基础 > 计算机网络

arduino 与 android 通过TCP进行字节收发

2015-11-17 16:50 519 查看
arduino

package cn.fstudio.wificracker;

public class BitConvert {
/**
* 灏嗕竴涓崟瀛楄妭鐨刡yte杞崲鎴�32浣嶇殑int
*
* @param b
*            byte
* @return convert result
*/
public static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}

/**
* 灏嗕竴涓崟瀛楄妭鐨凚yte杞崲鎴愬崄鍏繘鍒剁殑鏁�
*
* @param b
*            byte
* @return convert result
*/
public static String byteToHex(byte b) {
int i = b & 0xFF;
return Integer.toHexString(i);
}

/**
* 灏嗕竴涓�4byte鐨勬暟缁勮浆鎹㈡垚32浣嶇殑int
*
* @param buf
*            bytes buffer
* @param byte[]涓紑濮嬭浆鎹㈢殑浣嶇疆
* @return convert result
*/
public static long unsigned4BytesToInt(byte[] buf, int pos) {
int firstByte = 0;
int secondByte = 0;
int thirdByte = 0;
int fourthByte = 0;
int index = pos;
firstByte = (0x000000FF & ((int) buf[index+3]));
secondByte = (0x000000FF & ((int) buf[index + 2]));
thirdByte = (0x000000FF & ((int) buf[index + 1]));
fourthByte = (0x000000FF & ((int) buf[index ]));
index = index + 4;
return ((long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFL;
}

/**
* 灏�16浣嶇殑short杞崲鎴恇yte鏁扮粍
*
* @param s
*            short
* @return byte[] 闀垮害涓�2
* */
public static byte[] shortToByteArray(short s) {
byte[] targets = new byte[2];
for (int i = 0; i < 2; i++) {
int offset = (targets.length - 1 - i) * 8;
targets[i] = (byte) ((s >>> offset) & 0xff);
}
return targets;
}

/**
* 灏�32浣嶆暣鏁拌浆鎹㈡垚闀垮害涓�4鐨刡yte鏁扮粍
*
* @param s
*            int
* @return byte[]
* */
public static byte[] intToByteArray(int s) {
byte[] targets = new byte[2];
for (int i = 0; i < 4; i++) {
int offset = (targets.length - 1 - i) * 8;
targets[i] = (byte) ((s >>> offset) & 0xff);
}
return targets;
}

/**
* long to byte[]
*
* @param s
*            long
* @return byte[]
* */
public static byte[] longToByteArray(long s) {
byte[] targets = new byte[2];
for (int i = 0; i < 8; i++) {
int offset = (targets.length - 1 - i) * 8;
targets[i] = (byte) ((s >>> offset) & 0xff);
}
return targets;
}

/**32浣峣nt杞琤yte[]*/
public static byte[] int2byte(int res) {
byte[] targets = new byte[4];
targets[0] = (byte) (res & 0xff);// 鏈�浣庝綅
targets[1] = (byte) ((res >> 8) & 0xff);// 娆′綆浣�
targets[2] = (byte) ((res >> 16) & 0xff);// 娆¢珮浣�
targets[3] = (byte) (res >> 24);// 鏈�楂樹綅,鏃犵鍙峰彸绉汇��
return targets;
}

/**
* 灏嗛暱搴︿负2鐨刡yte鏁扮粍杞崲涓�16浣峣nt
*
* @param res
*            byte[]
* @return int
* */
public static int byte2int(byte[] res) {
// res = InversionByte(res);
// 涓�涓猙yte鏁版嵁宸︾Щ24浣嶅彉鎴�0x??000000锛屽啀鍙崇Щ8浣嶅彉鎴�0x00??0000
int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00); // | 琛ㄧず瀹変綅鎴�
return targets;
}
}


View Code
注意:

char c= mySerial.read();
RecCache=RecCache +(String)c;
遇到byte=0 时会发生错误

如果需要按byte接收数据,请采用
/article/4890325.html
的方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: