天天看点

java各种数据类型的方式

1、int 转String

第一种方式

int num = 2;

String str = “” + num;

第二种方式

String str2 = String.valueOf(num);

第三种方式

String str = Integer.toString(num);

2、String转int

第一种方式

String s = “27”;

int num = Integer.valueOf(s);

第二种方式

int num2 = Integer.parseInt(s);

3、String转byte

第一种方式

byte b = Byte.valueOf(s);

第二种方式

byte b2 = Byte.parseByte(s);

4、String转char[]

char[] c = s.toCharArray();

5、String转short

第一种方式

short sh = Short.valueOf(s);

第二种方式

short sh2 = Short.parseShort(s);

6、int 转short

short sh3 = (short) num;

7、String转byte[]

byte[] barr = s.getBytes();

8、int转byte[]

int转byte[]不能直接转需要定义一个方法:

/**
     * 整形int转byte[]      关键技术ByteArrayOutputStream和DataOutputStream
     * @param int
     * @return byte[]
     */
    public static byte[] intToByteArray(int n) {
        byte[] byteArray = null;
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            DataOutputStream dataOut = new DataOutputStream(byteOut);
            dataOut.writeInt(n);
            byteArray = byteOut.toByteArray();
            for (byte b : byteArray) {
                System.out.println(" " + b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArray;
    }
           

byte[] barr2 = intToByteArray(num);

9、byte[]转int

byte[]转int不可以直接转需要定义一个方法:

/**
     * 字节数组转换成整数 关键技术:ByteArrayInputStream和DataInputStream
     *
     * @param byteArray
     * 需要转换的字节数组
     * @return
     */
    public static int byteArrayToInt(byte[] byteArray) {
        int n = 0;
        try {
            ByteArrayInputStream byteInput = new ByteArrayInputStream(byteArray);
            DataInputStream dataInput = new DataInputStream(byteInput);
            n = dataInput.readInt();
            System.out.println("整数为: " + n);
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        return n;
    }
           

int num5 = byteArrayToInt(barr);

继续阅读