// 灵敏度
// ArrayBuffer转16进制字符串示例
function ab2hext(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}
// 字符串转为ArrayBuffer对象，参数为字符串
function str2ab(str) {
	var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
	var bufView = new Uint16Array(buf);
	for (var i = 0, strLen = str.length; i < strLen; i++) {
		bufView[i] = str.charCodeAt(i);
	}
	return buf;
}
//16进制的字符串 转换为整数
function hex2int(hex) {
	var len = hex.length,
		a = new Array(len),
		code;
	for (var i = 0; i < len; i++) {
		code = hex.charCodeAt(i);
		if (48 <= code && code < 58) {
			code -= 48;
		} else {
			code = (code & 0xdf) - 65 + 10;
		}
		a[i] = code;
	}

	return a.reduce(function(acc, c) {
		acc = 16 * acc + c;
		return acc;
	}, 0);
}
//16进制转有符号的整数
function hexToSignedInt(hex) {
	let two = parseInt(hex, 16).toString(2);
	let bitNum = hex.length * 4;
	if (two.length < bitNum) {
		while (two.length < bitNum) {
			two = "0" + two;
		}
	}

	if (two.substring(0, 1) == "0") {
		two = parseInt(two, 2);

		return two;
	} else {
		let two_unsign = "";
		two = parseInt(two, 2) - 1;
		two = two.toString(2);
		two_unsign = two.substring(1, bitNum);
		two_unsign = two_unsign.replace(/0/g, "z");
		two_unsign = two_unsign.replace(/1/g, "0");
		two_unsign = two_unsign.replace(/z/g, "1");
		two = parseInt(-two_unsign, 2);

		return two;
	}
}
//十六进制转ASCII码
function hexCharCodeToStr(hexCharCodeStr) {
	var trimedStr = hexCharCodeStr.trim();
	var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
	var len = rawStr.length;
	if (len % 2 !== 0) {
		alert("存在非法字符!");
		return "";
	}
	var curCharCode;
	var resultStr = [];
	for (var i = 0; i < len; i = i + 2) {
		curCharCode = parseInt(rawStr.substr(i, 2), 16);
		resultStr.push(String.fromCharCode(curCharCode));
	}
	return resultStr.join("");
}

//ASCII码转16进制
function strToHexCharCode(str) {
	if (str === "") {
		return "";
	} else {
		var hexCharCode = [];
		hexCharCode.push("0x");
		for (var i = 0; i < str.length; i++) {
			hexCharCode.push((str.charCodeAt(i)).toString(16));
		}
		return hexCharCode.join("");
	}
}

//16进制转字符串
function hexToString(str) {
	var trimedStr = str.trim();
	var rawStr =
		trimedStr.substr(0, 2).toLowerCase() === "0x" ?
		trimedStr.substr(2) :
		trimedStr;
	var len = rawStr.length;
	if (len % 2 !== 0) {
		// alert("Illegal Format ASCII Code!");
		return "";
	}
	var curCharCode;
	var resultStr = [];
	for (var i = 0; i < len; i = i + 2) {
		curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
		resultStr.push(String.fromCharCode(curCharCode));
	}
	return resultStr.join("");
}



function getRSSITransDistance(rssi) {
	return Math.pow(Math.E, (Math.abs(rssi) - 66.78) / 16.56);
}



export default {
	getRSSITransDistance,
	
	ab2hext,
	str2ab,
	hex2int,
	hexToSignedInt,
	hexCharCodeToStr,
	strToHexCharCode,
	hexToString

}
