16位无符号数(unsigned short)转10进制

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:24   2767   0

16位无符号数(unsigned short)转10进制://信号强度采用16位无符号数(unsigned short),数值越大信号越强, 单位db

0x00,0x19 -> 25db

16位unsigned short为2Byte,且无符号,则为0*16^3 + 0*16^2 + 1*16^1 + 9*16^0 = 25

思路是:(0x00,0x19)对应的高位为num[high]=0x00=0,低位为num[low]=0x19=25,要先把(0,25)->(0019)-,然后再计算结果。


//0x00,0x19 -> 入参为:0,25
private String toHexStr(int highByte, int lowByte){
 StringBuilder sb = new StringBuilder();
 if (highByte > 0) {
  String high = Integer.toHexString(highByte);
  if (high.length() < 2) {
   sb.append('0').append(high);
  } else {
   sb.append(high);
  }
 } else {
  sb.append("00");
 }

 if (lowByte > 0) {
  String low = Integer.toHexString(lowByte);
  if (low.length() < 2) {
   sb.append('0').append(low);
  } else {
   sb.append(low);
  }
 } else {
  sb.append("00");
 }
 return sb.toString();
}
 

//16进制的字符串 转 10进制的数
private int toDexNum(String hexStr){
 int num = 0;
 int numLen = hexStr.length();

 for(int i = 0; i < numLen; i++) {
  int temp1 = hexChar2DexNum(hexStr.charAt(i));
  int temp2 = (int)Math.pow(16, numLen-i-1);
  num += temp1 * temp2;
 }
//        Log.d(TAG, "toUnsignedShort: " + num + ", " + hexStr);
 return num;
}

//16进制的字符 转 10进制的数 
private int hexChar2DexNum(char ch){
 ch = Character.toLowerCase(ch);
 int temp = 0;
 if (ch >= '0' && ch <= '9'){
  temp = ch - '0';
 } else if (ch >= 'a' && ch <= 'f'){
  temp = ch - 'a' + 10;
 }
//        Log.d(TAG, "hexChar2DexNum: ch " + ch + ", num = " + temp);
 return temp;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP