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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值