數據轉換工具類彙總

數據工具類彙總

public class DataUtil {

    private static StringBuffer sbTime;
    private static String now, year, month, day, hour, min, ss;
    private static SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyyMMddHHmmssSSS");

    private static String resultString = null;
    private static String resultTrimData = null;

    public static DecimalFormat df = new DecimalFormat("0.00");

    public DataUtil() {

    }

    /**
     * 時間同步 取得當前的時間, 並轉爲需要的格式: 16進制String並以F4開頭
     */
    public static String getTimeFormat() {
        sbTime = new StringBuffer();
        now = null;
        now = sdf.format(new Date());
        year = Integer
                .toHexString(Integer.parseInt(now.substring(0, 4)) - 1900);
        now.substring(4, 6);
        month = Integer.toHexString(Integer.parseInt(now.substring(4, 6)));
        if (month.length() == 1)
            month = '0' + month;
        day = Integer.toHexString(Integer.parseInt(now.substring(6, 8)));
        if (day.length() == 1)
            day = '0' + day;
        hour = Integer.toHexString(Integer.parseInt(now.substring(8, 10)));
        if (hour.length() == 1)
            hour = '0' + hour;
        min = Integer.toHexString(Integer.parseInt(now.substring(10, 12)));
        if (min.length() == 1)
            min = '0' + min;
        ss = Integer.toHexString(Integer.parseInt(now.substring(12, 14)));
        if (ss.length() == 1)
            ss = '0' + ss;
        sbTime.append("F4");
        sbTime.append(year);
        sbTime.append(month);
        sbTime.append(day);
        sbTime.append(hour);
        sbTime.append(min);
        sbTime.append(ss);
        sbTime.append("00");
        now = sbTime.toString().toUpperCase();
        return now;
    }

    /**
     * 取得String字符的前兩位
     */
    public static String getTag(String data) {
        if (!data.isEmpty()) {
            resultString = data.substring(0, 2);
        }
        return resultString;
    }

    /**
     * 去除String字符中所有的空白符
     */
    public static String getTrimData(String data) {
        if (!data.isEmpty()) {
            resultTrimData = data.replaceAll("\\s*", "");
        }
        return resultTrimData;
    }

    /**
     * byte[]轉變爲16進制String字符, 每個字節2位, 不足補0
     */
    public static String getStringByBytes(byte[] bytes) {
        String result = null;
        String hex = null;
        if (bytes != null && bytes.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(bytes.length);
            for (byte byteChar : bytes) {
                hex = Integer.toHexString(byteChar & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                stringBuilder.append(hex.toUpperCase());
            }
            result = stringBuilder.toString();
        }
        return result;
    }

    /**
     * 把16進制String字符轉變爲byte[]
     */
    public static byte[] getBytesByString(String data) {
        byte[] bytes = null;
        if (data != null) {
            data = data.toUpperCase();
            int length = data.length() / 2;
            char[] dataChars = data.toCharArray();
            bytes = new byte[length];
            for (int i = 0; i < length; i++) {
                int pos = i * 2;
                bytes[i] = (byte) (charToByte(dataChars[pos]) << 4 | charToByte(dataChars[pos + 1]));
            }
        }
        return bytes;
    }

    /**
     * 取得在16進制字符串中各char所代表的16進制數
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 方法介紹
     */
    public static void helpInfo() {
        System.out.println("十進制轉成十六進制: Integer.toHexString(int i) ");
        System.out.println("十六進制轉成十進制: Integer.valueOf('FFFF',16).toString() ");
    }

    /**
     * 根據傳入的兩個double類型的時間戳, 後者比較大, 算出他們之間隔了多少小時
     */
    public static double getHours(double date1, double date2) {
        double hours = (date2 - date1) / (1000 * 60 * 60);
        hours = Double.parseDouble(df.format(hours));
        // hours = Math.round((hours * 100) / 100);
        return hours;
    }

    /**
     * 根據 步數(步), 身高(釐米), 體重(千克), 時間(小時)算出消耗的能量KCal(千卡) kcal = 體重 * 時間 * 指數(k) k
     * = 30 / 速度( N分鐘 / 400米) = 30 / 多少分鐘400米
     */
    public static double getKCal(int step, double height, double weight,
            double time) {
        double kcal = 0;
        // 步幅 = 身高 * 0.45 (米)
        double stride = (double) (height * 0.45 / 100);
        // 速度 = 時間(分鐘) / (步幅 * 步數(米) / 400)
        double speed = (time * 60) / (stride * step / 400);
        // 指數 = 30 / 速度(分鐘/400米)
        double k = 30 / speed;
        kcal = weight * time * k;
        kcal = Double.valueOf(df.format(kcal));
        return kcal;
    }

    /**
     * 
     * 根據 步數(步), 身高(釐米),步幅(釐米),體重(千克), 時間(小時)算出消耗的能量KCal(千卡) kcal = 體重 * 時間 * 指數(k) k
     * = 30 / 速度( N分鐘 / 400米) = 30 / 多少分鐘400米
     * @param step
     * @param height
     * @param stride
     * @param weight
     * @param time
     * @return
     */
    public static double getKCal(int step, double height, double stride,
            double weight, double time) {
        double kcal = 0;
        // 步幅 = 身高 * 0.45 (米)
        // double stride = (double) (height * 0.45 / 100);
        // 速度 = 時間(分鐘) / (步幅 * 步數(米) / 400)
        double speed = (time * 60) / (stride * step / 400);
        // 指數 = 30 / 速度(分鐘/400米)
        double k = 30 / speed;
        kcal = weight * time * k;
        kcal = Double.valueOf(df.format(kcal));
        return kcal;
    }

    /**
     * 根據傳過來的時間String轉成毫秒級的時間數據double型 數據格式可能爲2:00:25或者01:25
     */
    public static long getMillsTime(String time) {
        long hh, mm, ss;
        int l = time.length();
        if (l <= 5 && l > 0) {
            hh = 0;
            mm = Long.valueOf(time.substring(0, 2));
            ss = Long.valueOf(time.substring(3, 5));
            return (mm * 60 + ss) * 1000;
        } else if (l == 7) {
            hh = Long.valueOf(time.substring(0, 1));
            mm = Long.valueOf(time.substring(2, 4));
            ss = Long.valueOf(time.substring(5, 7));
            return (hh * 60 * 60 + mm * 60 + ss) * 1000;
        } else if (l == 8) {
            hh = Long.valueOf(time.substring(0, 2));
            mm = Long.valueOf(time.substring(3, 5));
            ss = Long.valueOf(time.substring(6, 8));
            return (hh * 60 * 60 + mm * 60 + ss) * 1000;
        } else {
            return 0;
        }
    }

    /**
     * 根據傳入的耗秒數, 轉換成爲HH:MM:SS的字符串返回
     */
    public static String getHHMMSS(long time) {
        String hhmmss = "00:00:00";
        StringBuffer bf = new StringBuffer();
        long hh = time / 1000 / 60 / 60;
        long mm = (time % (1000 * 60 * 60)) / 1000 / 60;
        long ss = ((time % (1000 * 60 * 60)) % (1000 * 60)) / 1000;

        if (hh < 0) {
            bf.append("00:");
        } else if (hh < 10) {
            bf.append("0" + hh + ":");
        } else {
            bf.append(hh + ":");
        }
        if (mm < 0) {
            bf.append("00:");
        } else if (mm < 10) {
            bf.append("0" + mm + ":");
        } else {
            bf.append(mm + ":");
        }
        if (ss < 0) {
            bf.append("00");
        } else if (ss < 10) {
            bf.append("0" + ss);
        } else {
            bf.append(ss);
        }
        hhmmss = bf.toString();
        System.out.println(hhmmss);
        return hhmmss;
    }

    /**
     * 根據傳入的時間mills和距離(千米)得出速度
     */
    public static double getSpeed(double mills, double dist) {
        double hours = 0;
        hours = (Double) (mills * 0.001 / 60 / 60);
        if (hours == 0) {
            return 0;
        }
        double speed = dist / hours;
        speed = Double.valueOf(df.format(speed));
        // hours = double.valueOf(df.format(hours));
        return speed;
    }

    /**
     * 根據用戶傳入的身高與步數, 返回用戶步行的里程
     */
    public static String getDisc(String height, String stepCount) {
        String dist = "0";
        double distance_dou = Double.valueOf(stepCount)
                * Double.valueOf(height) * 0.45 * 0.01 * 0.001;
        String distance_str = df.format(distance_dou);
        return distance_str;
    }

    /**
     * 根據傳入的當前步數與目標步數,計算完成的百分比
     */
    public static String getPercent(String currentStep, String targetStep) {
        double percent = Double.valueOf(currentStep)
                / Double.valueOf(targetStep) * 100;
        return df.format(percent);
    }

    /**
     * 根據傳入的提醒類型和電話號碼,返回字節數組
     * 
     * @param remindType
     *            提醒類型
     * @param phoneNumber
     *            電話號碼
     * @return
     */
    public static byte[] getBytesForRemind(String remindType, String phoneNumber) {
        StringBuffer remindStr = new StringBuffer();
        // 提醒的類型
        String type = Integer.toHexString(Integer.parseInt(remindType, 2));
        // 電話號碼的位數
        String length = Integer.toHexString(phoneNumber.length());

        remindStr.append("F1");
        remindStr.append(type);
        remindStr.append("000");
        remindStr.append(length.toUpperCase());
        // 對座機、手機號碼的處理
        phoneNumber = (phoneNumber.length() % 2) == 0 ? phoneNumber
                : phoneNumber + "0";
        remindStr.append(phoneNumber);
        System.out.println("提示數據協議:" + remindStr.toString());
        return getBytesByString(remindStr.toString());
    }

    /**
     * 傳入未接電話和未讀短信數
     * 
     * @param calls
     *            未接電話數
     * @param sms
     *            未讀短信數
     * @return 發出信號所需的字節數組
     */
    public static byte[] getSMS_CALL_Count(int calls, int sms) {
        StringBuffer sb = new StringBuffer();
        String missCall = Integer.toHexString(calls);
        String unReadSMS = Integer.toHexString(sms);
        sb.append("FA");
        // 拼未接電話數
        if (missCall.length() == 1) {
            sb.append("000");
            sb.append(missCall);
        } else if (missCall.length() == 2) {
            sb.append("00");
            sb.append(missCall);
        } else if (missCall.length() == 3) {
            sb.append("0");
            sb.append(missCall);
        } else if (missCall.length() == 4) {
            sb.append(missCall);
        }
        // 拼未讀短信數
        if (unReadSMS.length() == 1) {
            sb.append("000");
            sb.append(unReadSMS);
        } else if (unReadSMS.length() == 2) {
            sb.append("00");
            sb.append(unReadSMS);
        } else if (unReadSMS.length() == 3) {
            sb.append("0");
            sb.append(unReadSMS);
        } else if (unReadSMS.length() == 4) {
            sb.append(unReadSMS);
        }
        sb.append("000000");
        System.out.println("未接電話和未讀短信協議:" + sb.toString());
        return getBytesByString(sb.toString());
    }

    /**
     * 根據傳入的2個字節4位16進制字符比如FFFF, 計算返回int類型的絕對值
     */
    public static int hexStringX2bytesToInt(String hexString) {
        return binaryString2int(hexString2binaryString(hexString));
    }

    /**
     * 16進制轉換爲2進制
     */
    public static String hexString2binaryString(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0) {
            return null;
        }
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000"
                    + Integer.toBinaryString(Integer.parseInt(
                            hexString.substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }

    /**
     * 二進制轉爲10進制 返回int
     */
    public static int binaryString2int(String binarysString) {
        if (binarysString == null || binarysString.length() % 8 != 0) {
            return 0;
        }
        int result = Integer.valueOf(binarysString, 2);
        if ("1".equals(binarysString.substring(0, 1))) {
            System.out.println("這是個負數");
            char[] values = binarysString.toCharArray();
            for (int i = 0; i < values.length; i++) {
                if (values[i] == '1') {
                    values[i] = '0';
                } else {
                    values[i] = '1';
                }
            }
            binarysString = String.valueOf(values);
            result = Integer.valueOf(binarysString, 2) + 1;
        }

        return result;
    }

    /**
     * 
     * 二進制轉爲16進制
     */
    public static String binaryString2hexString(String bString) {
        if (bString == null || bString.equals("") || bString.length() % 8 != 0) {
            return null;
        }
        StringBuffer tmp = new StringBuffer();
        int iTmp = 0;
        for (int i = 0; i < bString.length(); i += 4) {
            iTmp = 0;
            for (int j = 0; j < 4; j++) {
                iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
            }
            tmp.append(Integer.toHexString(iTmp));
        }
        return tmp.toString();
    }

    /**
     * 根據傳入的X, Y, Z 算出 x平方 + y平方 + c 平方 的平方根值
     */
    public static int getXYZsquareRoot(int x, int y, int z) {
        return (int) Math.sqrt(x * x + y * y + z * z);
    }

    /**
     * 取當前的時間, 返回int型的小時, 比如 23:59:59 返回 23的int
     */
    public static int getCurrentHour() {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        return hour;
    }

    /**
     * 取得當前的分鐘數
     * @return
     */
    public static int getCurrentMinute() {
        Calendar c = Calendar.getInstance();
        int minute = c.get(Calendar.MINUTE);
        return minute;
    }

    /**
     * 取得當前的秒數
     */
    public static int getCurrentSecond() {
        Calendar c = Calendar.getInstance();
        int minute = c.get(Calendar.SECOND);
        return minute;
    }

    /**
     * 傳入天氣及溫度的String, 返回協議的bytes[]
     */
    public static byte[] getWeatherInfo(String weather, String temp) {

        Map<String, String> weatherMap = new HashMap<String, String>();

        weatherMap.put("晴", "01");
        weatherMap.put("陰", "02");
        weatherMap.put("多雲", "03");
        weatherMap.put("小雨", "04");
        weatherMap.put("中雨", "05");
        weatherMap.put("小到中雨", "05");
        weatherMap.put("大雨", "06");
        weatherMap.put("中到大雨", "06");
        weatherMap.put("雷陣雨", "07");
        weatherMap.put("陣雨", "07");
        weatherMap.put("暴雨", "07");
        weatherMap.put("大暴雨", "07");
        weatherMap.put("特大暴雨", "07");
        weatherMap.put("大到暴雨", "07");
        weatherMap.put("暴雨到大暴雨", "07");
        weatherMap.put("暴雨到特大暴雨", "07");
        weatherMap.put("小雪", "08");
        weatherMap.put("中雪", "09");
        weatherMap.put("小到中雪", "09");
        weatherMap.put("大雪", "0A");
        weatherMap.put("陣雪", "0A");
        weatherMap.put("暴雪", "0A");
        weatherMap.put("中到大雪", "0A");
        weatherMap.put("大到暴雪", "0A");
        weatherMap.put("雨夾雪", "0B");
        weatherMap.put("霧", "0C");
        weatherMap.put("冰雹", "0D");
        weatherMap.put("凍雨", "0D");
        weatherMap.put("雷陣雨伴有冰雹", "0E");
        weatherMap.put("塵埃", "0F");
        weatherMap.put("沙塵暴", "0F");
        weatherMap.put("浮塵", "0F");
        weatherMap.put("揚沙", "0F");
        weatherMap.put("強沙塵暴", "0F");
        weatherMap.put("霾", "0F");
        weatherMap.put("熱帶風暴", "10");
        weatherMap.put("風", "11");
        weatherMap.put("大風", "12");
        weatherMap.put("狂風", "13");
        weatherMap.put("龍捲風", "14");
        weatherMap.put("雷暴", "15");
        weatherMap.put("猛烈雷暴", "16");
        byte[] bytes = null;
        StringBuilder sb = new StringBuilder();
        sb.append("F2");
        // 天氣
        String weatherCode = weatherMap.get(weather);
        if (weatherCode != null) {
            sb.append(weatherCode);
        } else {
            sb.append("03");
        }
        // System.out.println("收到的天氣是 : " + weather + ", 其轉換爲代碼是 : " +
        // weatherCode
        // + "測試天氣 : " + weatherMap.get("陣雨"));
        // 溫度單位
        Integer intTemp = Integer.valueOf(temp, 10);
        if (intTemp < 0) {
            sb.append("40");
        } else {
            sb.append("C0");
        }
        // 溫度值
        String hexTemp = Integer.toHexString(Math.abs(intTemp)).toString();
        sb.append(hexTemp);
        // 不足補零
        sb.append("00000000");

        // System.out.println("send weather info : " + sb.toString());

        return getBytesByString(sb.toString());
    }

    /**
     * 根據傳入的數,計算返回整百值
     * 如傳入156,返回200
     * @param snore_count
     * @return
     */
    public static int getMaxbySnorecount(int snore_count){
        String str = (snore_count + "");
        int length = str.length();
        if (length < 3) {
            return 100;
        } else {
            str = str.substring(0, length - 2);
            int max = (Integer.parseInt(str) + 1) * 100;
            System.out.println("轉換後的max:" + max);
            return max;
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章