欢迎大家访问我的个人网站 萌萌的IT人,后续所有的文章都会在此发布
--------------------------------------------------------------------------------------------
package com;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestByte {
/**
* ip转化成4个字节进行存储,然后再把四个字节转换成byte
*/
public static void ipTobyte()
{
String ip="222.168.205.83";
String[] ips = ip.split("\\.");
int ip1 = Integer.valueOf(ips[0]);
int ip2 = Integer.valueOf(ips[1]);
int ip3 = Integer.valueOf(ips[2]);
int ip4 = Integer.valueOf(ips[3]);
System.out.println(ip1);
System.out.println(ip2);
System.out.println(ip3);
System.out.println(ip4);
byte b1 = (byte)ip1;
byte b2 = (byte)ip2;
byte b3 = (byte)ip3;
byte b4 = (byte)ip4;
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println(b4);
// int 转byte之后 操作127的数字将全部变成负数形式,如果想转成原来的 int值 直接 & 0xFF
System.out.println(b1 & 0xFF);
System.out.println(b2 & 0xFF);
System.out.println(b3 & 0xFF);
System.out.println(b4 & 0xFF);
}
public static void byteToIP()
{
}
/**
* long -> 4位字节 -> long
* 主要是做了一个数据压缩算法
* 比如说一个ip可以直接存储成4个字节
*/
public static void numToBinaryString()
{
//源数字
long num = 98786657;
//转化成二进制串
String binary = Long.toBinaryString(num);
System.out.println(binary);
int length = 32-binary.length();
//补充到32位
for(int i=0;i<length;i++)
{
binary = '0'+binary;
}
System.out.println(binary);
System.out.println(binary.length());
//分割成四个字节 (一个字节8位)
String b1 = binary.substring(0, 8);
String b2 = binary.substring(8, 16);
String b3 = binary.substring(16, 24);
String b4 = binary.substring(24, 32);
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println(b4);
//8位转化成一个字节
int a1 = Integer.valueOf(b1, 2);
int a2 = Integer.valueOf(b2, 2);
int a3 = Integer.valueOf(b3, 2);
int a4 = Integer.valueOf(b4, 2);
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
System.out.println(a4);
byte c1 = (byte)a1;
byte c2 = (byte)a2;
byte c3 = (byte)a3;
byte c4 = (byte)a4;
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);
//把字节转化成long
long ret = 0;
ret |= c4 & 0xFF;
ret |= (c3<<8) & 0xFF00;
ret |= (c2<<16) & 0xFF0000;
ret |= (c1<<24) & 0xFF000000;
System.out.println(ret);
// Integer.toBinaryString(c4&0xFF);
// System.out.println();
}
/**
* 把字节写入文件,看看是啥效果
* @throws IOException
*/
public static void writeByteToFile() throws IOException
{
File file = new File("a.txt");
FileOutputStream fis = new FileOutputStream(file);
fis.write(-106);
fis.write(-38);
fis.write(0);
fis.write(11);
fis.flush();
System.out.println(file.getAbsolutePath());
}
public static void main(String[] args) throws IOException
{
// TestByte.writeByteToFile();
// TestByte.numToBinaryString();
TestByte.ipTobyte();
}
}