ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

commons.tools.utils.{ConvertUtils} 转换工具类

2022-06-17 11:01:02  阅读:154  来源: 互联网

标签:return int utils commons ConvertUtils static byte public rect


1、问题

  项目的过程中涉及到许多数据转化,比如int转byte等,然后为了简化单独做类一个工具类,里面有大多数数据转化的方法可以直接调用

还有一种是进行对象转换sourceToTarget内部利用BeanUtils.copyProperties(bean, name, value)(关于BeanUtils.下回分解)

2、代码实现

public class ConvertUtil {
    private static NV21ToBitmap nv21ToBitmap;
    public static int byteArrayToInt(byte[] bytes) {
        int value = 0;
        // 由高位到低位
        for (int i = 0; i < bytes.length; i++) {
            int shift = (bytes.length - 1 - i) * 8;
            value += (bytes[i] & 0x000000FF) << shift;// 往高位游
        }
        return value;
    }
 
    public static int byteArrayToInt(byte[] bytes, int index, int len) {
        int value = 0;
        // 由高位到低位
        for (int i = 0; i < len; i++) {
            int shift = (len - 1 - i) * 8;
            value += (bytes[index + i] & 0x000000FF) << shift;// 往高位游
        }
        return value;
    }
 
    public static byte[] intToByteArray(int it, int byteLen) {
        byte[] result = new byte[byteLen];
 
        for(int i = 0; i < byteLen; ++i) {
            result[byteLen - i - 1] = (byte)(it >> 8 * i & 255);
        }
        return result;
    }
 
    public static byte[] longToByteArray(long it, int byteLen) {
        byte[] result = new byte[byteLen];
 
        for(int i = 0; i < byteLen; ++i) {
            result[byteLen - i - 1] = (byte)(it >> 8 * i & 65535);
        }
 
        return result;
    }
 
    public static String bytesToHexString(byte[] src, int start, int len) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src != null && len > 0) {
            for(int i = start; i < start + len; ++i) {
                int v = src[i] & 255;
                String hv = Integer.toHexString(v).toUpperCase();
                if (hv.length() < 2) {
                    stringBuilder.append(0);
                }
 
                stringBuilder.append(hv);
            }
 
            return stringBuilder.toString();
        } else {
            return null;
        }
    }
 
    public static int byteToStringInt(byte b) {
        return Integer.valueOf(bytesToHexString(new byte[]{b}, 0, 1));
    }
 
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString != null && !hexString.equals("")) {
            hexString = hexString.toUpperCase();
            int length = hexString.length() / 2;
            char[] hexChars = hexString.toCharArray();
            byte[] d = new byte[length];
 
            for(int i = 0; i < length; ++i) {
                int pos = i * 2;
                d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
            }
 
            return d;
        } else {
            return null;
        }
    }
    private static byte charToByte(char c) {
        return (byte)"0123456789ABCDEF".indexOf(c);
    }
 
    public static byte[] float2byte(float f) {
         // 把float转换为byte[]
         int fbit = Float.floatToIntBits(f);
         byte[] b = new byte[4];
         for (int i = 0; i < 4; i++) {
             b[i] = (byte) (fbit >> (24 - i * 8));
         }
         // 翻转数组
         int len = b.length;
         // 建立一个与源数组元素类型相同的数组
         byte[] dest = new byte[len];
         // 为了防止修改源数组,将源数组拷贝一份副本
         System.arraycopy(b, 0, dest, 0, len);
         byte temp;
         // 将顺位第i个与倒数第i个交换
         for (int i = 0; i < len / 2; ++i) {
             temp = dest[i];
             dest[i] = dest[len - i - 1];
             dest[len - i - 1] = temp;
         }
         return dest;
    }
 
    public static float byte2float(byte[] b) {
        int l;
        l = b[0];
        l &= 0xff;
        l |= ((long) b[1] << 8);
        l &= 0xffff;
        l |= ((long) b[2] << 16);
        l &= 0xffffff;
        l |= ((long) b[3] << 24);
        return Float.intBitsToFloat(l);
    }
 
    public static Bitmap createQRCode(byte[] bytes, int widthPix, int heightPix) {
        try {
            String content =hexToString(bytesToHexString(bytes, 0, bytes.length));
 
            // 配置参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 容错级别
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 图像数据转换,使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
                    heightPix, hints);
            int[] pixels = new int[widthPix * heightPix];
            // 下面这里按照二维码的算法,逐个生成二维码的图片,
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < heightPix; y++) {
                for (int x = 0; x < widthPix; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * widthPix + x] = 0xff000000;
                    } else {
                        pixels[y * widthPix + x] = 0xffffffff;
                    }
                }
            }
            // 生成二维码图片的格式,使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public static String hexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        for (int count = 0; count < hex.length() - 1; count += 2) {
            String output = hex.substring(count, (count + 2));    //grab the hex in pairs
            int decimal = Integer.parseInt(output, 16);    //convert hex to decimal
            sb.append((char) decimal);    //convert the decimal to character
        }
        return sb.toString();
    }
 
    public static int dip2Px(int dip, Context context) {
        // px/dip = density;
        // density = dpi/160
        // 320*480 density = 1 1px = 1dp
        // 1280*720 density = 2 2px = 1dp
        float density = context.getResources().getDisplayMetrics().density;
        int px = (int) (dip * density + 0.5f);
        return px;
    }
 
    public static short bytes2Short(byte[] b, int index) {
        return (short) (((b[index + 1] << 8) | b[index + 0] & 0xff));
    }
 
    public static byte[] getBytesFrombytes(byte[] bytes, int index, int len) {
        byte[] newBytes = new byte[len];
        System.arraycopy(bytes, index, newBytes, 0, len);
        return newBytes;
    }
 
    public static boolean equals(byte[] data0, byte[] data1) {
        if (data0.length != data1.length){
            return false;
        }
        for(int i = 0; i < data1.length; i++){
            if (data0[i] != data1[i]){
                return false;
            }
        }
        return true;
    }
 
    public static boolean isDateExpire(Date currentDate, byte cardDay, byte cardMonth, byte cardYear) {
        int currentYear = currentDate.getYear() - 2000;
        if (currentYear == cardYear){
            if (cardMonth == currentDate.getMonth()){
                return currentDate.getDay() > cardDay;
            }else {
                return currentDate.getMonth() > cardMonth;
            }
        }else {
            return currentYear > cardYear;
        }
    }
 
    public static void setNv21ToBitmap(Context context){
        nv21ToBitmap = new NV21ToBitmap(context);
    }
 
    public static Bitmap nv21ToBitmap(byte[] nv21, int width, int height) {
        return nv21ToBitmap.nv21ToBitmap(nv21, width, height);
    }
 
 
    public static byte[] base64ToBytes(String faceFeature) {
        return Base64.decode(faceFeature, Base64.NO_WRAP);
    }
 
    public static Bitmap cropBitmap(Bitmap bitmap, Rect rect) {
        int x = rect.left;
        if (rect.left - 20 > 0){
            x = rect.left - 20;
        }
        int y = rect.right;
        if (rect.top - 40 > 0){
            y = rect.top-40;
        }
        int width = rect.right - rect.left;
        if ((rect.right - rect.left + 40 + x) < bitmap.getWidth() && (rect.right - rect.left + 40) < bitmap.getWidth()){
            width = rect.right - rect.left + 40;
        }
        int height = rect.bottom - rect.top;
        if ((rect.bottom - rect.top+80+ y) < bitmap.getHeight() &&  (rect.bottom - rect.top+80) < bitmap.getHeight()){
            height = rect.bottom - rect.top+80;
        }
        return Bitmap.createBitmap(bitmap, x, y, width, height, null, false);
    }
 
    public static String asciiToString(char code) {
        StringBuffer sbu = new StringBuffer();
        sbu.append((char) code);
        return sbu.toString();
    }
}

进行对象转换sourceToTarget代码如下

    public static <T> T sourceToTarget(Object source, Class<T> target){
        if(source == null){
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            logger.error("convert error ", e);
        }

        return targetObject;
    }

 

标签:return,int,utils,commons,ConvertUtils,static,byte,public,rect
来源: https://www.cnblogs.com/origin-zy/p/16384965.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有