知乎專欄 | 多維度架構 | | | 微信號 netkiller-ebook | | | QQ群:128659835 請註明“讀者” |
數據類型的最大值和最小值。
基本類型:int 二進制位數:32 包裝類:java.lang.Integer 最小值:Integer.MIN_VALUE= -2147483648 (-2的31次方) 最大值:Integer.MAX_VALUE= 2147483647 (2的31次方-1) 基本類型:short 二進制位數:16 包裝類:java.lang.Short 最小值:Short.MIN_VALUE=-32768 (-2的15此方) 最大值:Short.MAX_VALUE=32767 (2的15次方-1) 基本類型:long 二進制位數:64 包裝類:java.lang.Long 最小值:Long.MIN_VALUE=-9223372036854775808 (-2的63次方) 最大值:Long.MAX_VALUE=9223372036854775807 (2的63次方-1) 基本類型:float 二進制位數:32 包裝類:java.lang.Float 最小值:Float.MIN_VALUE=1.4E-45 (2的-149次方) 最大值:Float.MAX_VALUE=3.4028235E38 (2的128次方-1) 基本類型:double 二進制位數:64 包裝類:java.lang.Double 最小值:Double.MIN_VALUE=4.9E-324 (2的-1074次方) 最大值:Double.MAX_VALUE=1.7976931348623157E308 (2的1024次方-1)
十進制轉成十六進制: Integer.toHexString(int i) 十進制轉成八進制 Integer.toOctalString(int i) 十進制轉成二進制 Integer.toBinaryString(int i) 十六進制轉成十進制 Integer.valueOf("FFFF",16).toString() 八進制轉成十進制 Integer.valueOf("876",8).toString() 二進制轉十進制 Integer.valueOf("0101",2).toString() 有什麼方法可以直接將2,8,16進制直接轉換為10進制的嗎? java.lang.Integer類 parseInt(String s, int radix) 使用第二個參數指定的基數,將字元串參數解析為有符號的整數。 examples from jdk: parseInt("0", 10) returns 0 parseInt("473", 10) returns 473 parseInt("-0", 10) returns 0 parseInt("-FF", 16) returns -255 parseInt("1100110", 2) returns 102 parseInt("2147483647", 10) returns 2147483647 parseInt("-2147483648", 10) returns -2147483648 parseInt("2147483648", 10) throws a NumberFormatException parseInt("99",throws a NumberFormatException parseInt("Kona", 10) throws a NumberFormatException parseInt("Kona", 27) returns 411787 例二 int i=100; String binStr=Integer.toBinaryString(i); String otcStr=Integer.toOctalString(i); String hexStr=Integer.toHexString(i); System.out.println(binStr); 例二 Integer factor = Integer.valueOf(args[0]); String s; s = String.format("%d", factor); System.out.println(s); s = String.format("%x", factor); System.out.println(s); s = String.format("%o", factor); System.out.println(s); 其他方法: Integer.toHexString(你的10進制數); 例如 String temp = Integer.toHexString(75); 輸出temp就為 4b
Java 11 增加了一系列的字元串處理方法,如以下所示。
// 判斷字元串是否為空白 " ".isBlank(); // true // 去除首尾空格 " Javastack ".strip(); // "Javastack" // 去除尾部空格 " Javastack ".stripTrailing(); // " Javastack" // 去除首部空格 " Javastack ".stripLeading(); // "Javastack "
package cn.netkiller.test; public class Test { public static void main(String[] args) { String string = new String("http://www.netkiller.cn"); System.out.println("查找字元 . 第一次出現的位置: " + string.indexOf('.')); System.out.println("從第15個字元位置查找字元 . 出現的位置:" + string.indexOf('.', 15)); } }
public String randomString(String chars, int length) { Random rand = new Random(); StringBuilder buf = new StringBuilder(); for (int i = 0; i < length; i++) { buf.append(chars.charAt(rand.nextInt(chars.length()))); } return buf.toString(); } /** * 獲取4位隨機驗證碼 * @return */ public static String getValidationCode(){ return String.valueOf((new Random().nextInt(8999) + 1000)); } /** * 獲取6位隨機驗證碼 * @return */ public static String getValidationCode(){ return String.valueOf((new Random().nextInt(899999) + 100000)); }
public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("2010-09-11T20:00:30".replace("T", " ")); } }
{"status":0,"message":"","bankcode":"ABOC;IBC;CCTB;ICBC"} 轉換後 {\"status\":0,\"message\":\"\",\"bankcode\":\"ABOC;IBC;CCTB;ICBC\"}
package test; public class str { public static void main(String[] args) { String jsonString = "{\"status\":0,\"message\":\"\",\"bankcode\":\"ABOC;IBC;CCTB;ICBC\"}"; System.out.println(jsonString); System.out.println(jsonString.replace("\"", "\\\"")); } }
查找特定字元並替換為找到的內容
package cn.netkiller.type; public class ragexTest { public ragexTest() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub String str = "<html>Netkiller</html>"; String regex = "<html>|</html>"; //運行結果返回 Netkiller System.out.println(str.replaceAll(regex, "")); // 運行結果返回 Neo System.out.println("CN/NETKILLER/WWW/Neo_Chen".replaceAll(".*/(.+)_Chen", "$1")); } }
例如: String str = "helloword!!!"; System.out.println(str.substring(1,4)); System.out.println(str.substring(3,5)); System.out.println(str.substring(0,4)); 將得到結果為: ell lo hell
Timestamp轉化為String:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //定義格式,不顯示毫秒 Timestamp now = new Timestamp(System.currentTimeMillis()); //獲取系統當前時間 String str = df.format(now);
String轉化為Timestamp:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = df.format(new Date()); Timestamp ts = Timestamp.valueOf(time);
java11對String類新增了strip,stripLeading以及stripTrailing方法,除了strip相關的方法還新增了isBlank、lines、repeat(int)等方法
@Test public void testStrip(){ String text = " \u2000a b "; Assert.assertEquals("a b",text.strip()); Assert.assertEquals("\u2000a b",text.trim()); Assert.assertEquals("a b ",text.stripLeading()); Assert.assertEquals(" \u2000a b",text.stripTrailing()); }
String string = "佛山市123南海區ABC精密abc機械有限公司,"; String clean = string.replaceAll("\\P{Print}", ""); System.out.println(clean);
Unicode 碼表 https://www.ssec.wisc.edu/~tomw/java/unicode.html
String string = "2017-12-18 netkiller http://www.netkiller.cn - 網站正常"; System.out.println(string.replaceAll("[^\u4e00-\u9fa5]", ""));
java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp 區別
package cn.netkiller.java.date; /** * Hello world! * */ public class App { public static void main(String[] args) { System.out.println("Hello World!"); // Get standard date and time java.util.Date utilDate = new java.util.Date(); long javaTime = utilDate.getTime(); System.out.println("The Java Date is:" + utilDate.toString()); // Get and display SQL DATE java.sql.Date sqlDate = new java.sql.Date(javaTime); System.out.println("The SQL DATE is: " + sqlDate.toString()); // Get and display SQL TIME java.sql.Time sqlTime = new java.sql.Time(javaTime); System.out.println("The SQL TIME is: " + sqlTime.toString()); // Get and display SQL TIMESTAMP java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(javaTime); System.out.println("The SQL TIMESTAMP is: " + sqlTimestamp.toString()); } }
The Java Date is:Thu Aug 24 16:51:57 CST 2017 The SQL DATE is: 2017-08-24 The SQL TIME is: 16:51:57 The SQL TIMESTAMP is: 2017-08-24 16:51:57.234
public static void main(String[] args) { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //get current date time with Date() Date date = new Date(); System.out.println(dateFormat.format(date)); //get current date time with Calendar() Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime())); }
Timestamp timestamp = new Timestamp(System.currentTimeMillis()); Date date = new Date(); Timestamp timestamp = new Timestamp(date.getTime());
package cn.netkiller.example; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; public class TimeZoneTest { public TimeZoneTest() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); TimeZone timeZone = TimeZone.getTimeZone("Asia/Harbin"); Date date = new Date(); Timestamp timestamp = new Timestamp(date.getTime()); System.out.println(timestamp); timestamp.setHours(timestamp.getHours()+8); System.out.println(timestamp); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); System.out.println(simpleDateFormat.format(date)); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Harbin")); System.out.println(simpleDateFormat.format(date)); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.setTimeZone(timeZone); System.out.println(simpleDateFormat.format(calendar.getTime())); } }
package cn.netkiller.example; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDate { public StringToDate() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = "2008-8-8 8:8:8"; try { Date date = formatter.parse(dateString); System.out.println(date); System.out.println(formatter.format(date)); } catch (ParseException e) { e.printStackTrace(); } } }
package cn.netkiller.example; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class DateCompare { public DateCompare() { // TODO Auto-generated constructor stub } public void fun1() throws InterruptedException { Date d1 = new Date(); Thread.sleep(5000); Date d2 = new Date(); if (d1.before(d2)) { System.out.println(String.format("%s < %s", d1.toString(), d2.toString())); } else { System.out.println(String.format("%s > %s", d1.toString(), d2.toString())); } if (d2.after(d1)) { System.out.println(String.format("%s > %s", d2.toString(), d1.toString())); } System.out.println(String.format("%s : %s => %d", d2.toString(), d1.toString(), d1.compareTo(d2))); System.out.println(String.format("%s : %s => %d", d1.toString(), d2.toString(), d2.compareTo(d1))); } public void fun2() throws InterruptedException { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date1 = new Date(); Date date2 = new Date(); String s1 = dateFormat.format(date1); String s2 = dateFormat.format(date2); System.out.println(String.format("%s : %s => %d", s1, s2, s1.compareTo(s2))); date1 = new Date(); Thread.sleep(5000); date2 = new Date(); s1 = dateFormat.format(date1); s2 = dateFormat.format(date2); System.out.println(String.format("%s : %s => %d", s1, s2, s1.compareTo(s2))); System.out.println(String.format("%s : %s => %d", s2, s1, s2.compareTo(s1))); System.out.println(); } public void fun3() throws InterruptedException, ParseException { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //Date time = formatter.parse("2016-09-27 16:29"); Date time = formatter.parse("2016-08-09 09:15"); Date startDate = formatter.parse("2016-08-09 09:15"); Date endDate = formatter.parse("2016-09-27 16:30"); if (time.before(startDate) || time.after(endDate)) { System.out.println("Skip"); } } public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub DateCompare dateCompare = new DateCompare(); dateCompare.fun1(); System.out.println(); dateCompare.fun2(); System.out.println(); dateCompare.fun3(); } }
Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH )+1; System.out.println(year + "年 " + month + "月");
public Date getToday(String time) { final Calendar cal = Calendar.getInstance(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd " + time); DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = fmt.parse(dateFormat.format(cal.getTime())); } catch (ParseException e) { e.printStackTrace(); } return date; } private Date addOneDay(Date date, int day) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, day); return cal.getTime(); }
package cn.netkiller.date; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Yesterday { public Yesterday() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub Yesterday yesterday = new Yesterday(); System.out.println(yesterday.yesterday()); System.out.println(yesterday.getYesterday("00:00:00")); System.out.println(yesterday.getYesterday("23:59:59")); } private Date yesterday() { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); return cal.getTime(); } private Date getYesterday(String time) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd "+time); DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = fmt.parse(dateFormat.format(yesterday())); } catch (ParseException e) { e.printStackTrace(); } return date; } }
LocalDateTime localDateTime = LocalDateTime.of(2016, 1, 1, 13, 55); ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai")); Date date = Date.from(zonedDateTime.toInstant()); Instant instant = Instant.ofEpochMilli(date.getTime()); LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC); Instant instant = ldt.toInstant(ZoneOffset.UTC); Date date = Date.from(instant);
一定字元串數組
String[] str={"AAA","BBB","CCC"}; String str[]={"AAA","BBB","CCC"};
String to Array
package cn.netkiller.java; public class StringToArray { public static void main(String[] args) { // TODO Auto-generated method stub String str="a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"; String[] array = null; array = str.split(","); for(int i=0; i<array.length; i++){ System.out.println(array[i]); } } }
public static void main(String[] args) { try { for (String arg : args) { System.out.println(arg); } } catch (Exception e) { System.out.println(e.getMessage()); } }
package cn.netkiller.java; import java.util.Arrays; public class ArrayToString { public static void main(String[] args) { String[] array = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; System.out.println(Arrays.toString(array)); System.out.println(Arrays.toString(array).replaceAll(", |\\[|\\]", "")); } }
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}}; System.out.println(Arrays.toString(deepArray)); //output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922] System.out.println(Arrays.deepToString(deepArray)); Output: [[John, Mary], [Alice, Bob]]
float 不能直接做減法運算
float a = 77.22f; float b = 77.2f; System.out.println((float)a-b); System.out.println((float)a+b); 輸出結果為: 0.020004272 154.42
package cn.netkiller.example; import java.math.BigDecimal; public class Math { public Math() { // TODO Auto-generated constructor stub } public static void main(String[] args) { float a = 77.22f; float b = 77.2f; System.out.println((float) a + b); System.out.println((float) a - b); System.out.println((float) a * b); System.out.println((float) a / b); System.out.println("-------------"); System.out.println(add(a, b)); System.out.println(sub(a, b)); System.out.println(mul(a, b)); System.out.println(div(a, b)); } public static float add(float v1, float v2) { BigDecimal b1 = new BigDecimal(Float.toString(v1)); BigDecimal b2 = new BigDecimal(Float.toString(v2)); return b1.add(b2).floatValue(); } public static float sub(float v1, float v2) { BigDecimal b1 = new BigDecimal(Float.toString(v1)); BigDecimal b2 = new BigDecimal(Float.toString(v2)); return b1.subtract(b2).floatValue(); } public static float mul(float v1, float v2) { BigDecimal b1 = new BigDecimal(Float.toString(v1)); BigDecimal b2 = new BigDecimal(Float.toString(v2)); return b1.multiply(b2).floatValue(); } public static float div(float v1, float v2) { return div(v1, v2, 5); } public static float div(float v1, float v2, int scale) { if (scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Float.toString(v1)); BigDecimal b2 = new BigDecimal(Float.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).floatValue(); } public static float round(float v, int scale) { if (scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Float.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue(); } }
package cn.netkiller.example; import java.math.BigDecimal; public class Math { public Math() { // TODO Auto-generated constructor stub } public static double add(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2).doubleValue(); } public static double sub(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2).doubleValue(); } public static double mul(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2).doubleValue(); } public static double div(double v1, double v2) { return div(v1, v2, 8); } public static double div(double v1, double v2, int scale) { if (scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static double round(double v, int scale) { if (scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } }
package cn.netkiller.example; import java.math.BigDecimal; public class BigDecimalTest { public BigDecimalTest() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub BigDecimal first = new BigDecimal("1.0"); BigDecimal second = new BigDecimal("1.77"); System.out.println(String.format("%s, %s", first, second)); if (first.equals(second)) System.out.println("equals: true"); else System.out.println("equals: false"); if (first.compareTo(second) == 0) System.out.println("compareTo: true"); else System.out.println("compareTo: false"); BigDecimal zero = new BigDecimal("0"); BigDecimal one = new BigDecimal("1"); BigDecimal minus = new BigDecimal("-1"); if (zero.compareTo(one) < 0) System.out.println("比較演算子[ < ]: true"); if (one.compareTo(one) == 0) System.out.println("比較演算子[ == ]: true"); if (zero.compareTo(minus) > 0) System.out.println("比較演算子[ > ]: true"); if (zero.compareTo(minus) >= 0) System.out.println("比較演算子[ >= ]: true"); if (zero.compareTo(minus) != 0) System.out.println("比較演算子[ != ]: true"); if (zero.compareTo(one) <= 0) System.out.println("比較演算子[ <= ]: true"); } }
有時會輸出 1E+2,如果你不希望這種科學計數法輸出可以使用 toPlainString() 替代 toString() System.out.println( new BigDecimal("100.000").stripTrailingZeros().toPlainString());
package cn.netkiller.example.test; import java.math.BigDecimal; import java.math.BigInteger; public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub int decimal = 4; BigInteger amount = BigInteger.valueOf(10000000000L); BigDecimal balance = new BigDecimal(amount); BigDecimal point = new BigDecimal(0.1 / Math.pow(10, decimal)); balance = balance.multiply(point); System.out.println(balance); } }
發現輸出有問題 100000.000000000008180305391403130954586231382563710212707519531250000000000
換種方法
package cn.netkiller.example.test; import java.math.BigDecimal; import java.math.BigInteger; public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub // String i = Integer.valueOf("0x57c457",16).toString(); // System.out.println(i); int decimal = 6; BigInteger amount = BigInteger.valueOf(10000000000L); System.out.println(amount); String tmp = amount.toString(); String number = new StringBuffer(tmp).insert(tmp.length() - decimal, ".").toString(); BigDecimal balance = new BigDecimal(number); System.out.println(balance); } }
最佳方案
int decimal = 6; System.out.println(BigDecimal.TEN.pow(decimal)); BigDecimal balance1 = new BigDecimal("1234"); BigDecimal value = balance1.divide(BigDecimal.TEN.pow(decimal)); System.out.println(value); BigDecimal balance2 = new BigDecimal("12.107"); BigDecimal value2 = balance2.multiply(BigDecimal.TEN.pow(decimal)).setScale(0, RoundingMode.DOWN); System.out.println(value2);
String str = Integer.toString(j); str = new StringBuilder(str).insert(str.length()-2, ".").toString(); Or if you need synchronization use the StringBuffer with similar usage : String str = Integer.toString(j); str = new StringBuffer(str).insert(str.length()-2, ".").toString();
class EnumExample1{ public enum Season { WINTER, SPRING, SUMMER, FALL } public static void main(String[] args) { for (Season s : Season.values()) System.out.println(s); } }
package cn.netkiller.api.util; public enum HttpMethod { GET("GET"), POST("POST"), PUT("PUT"), PATCH("PATCH"), DELETE("DELETE"); private String value; private HttpMethod(String value) { this.value = value; } public String toString() { return value; } }
byte[] bytes = "Helloworld!!! - http://www.netkiller.cn".getBytes(); String str = new String(bytes, StandardCharsets.UTF_8); System.out.println(str);
int a= 120; byte b= (byte)a;
private byte[] bigIntToByteArray( final int i ) { BigInteger bigInt = BigInteger.valueOf(i); return bigInt.toByteArray(); }
private byte[] intToByteArray ( final int i ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeInt(i); dos.flush(); return bos.toByteArray(); }
private byte[] intToBytes( final int i ) { ByteBuffer bb = ByteBuffer.allocate(4); bb.putInt(i); return bb.array(); }
位移操作
private static byte[] intToBytes(final int a) { return new byte[] { (byte)((data >> 24) & 0xff), (byte)((data >> 16) & 0xff), (byte)((data >> 8) & 0xff), (byte)((data >> 0) & 0xff), }; }
private int convertByteArrayToInt(byte[] intBytes){ ByteBuffer byteBuffer = ByteBuffer.wrap(intBytes); return byteBuffer.getInt(); }
private int convertByteArrayToInt(byte[] data) { if (data == null || data.length != 4) return 0x0; // ---------- return (int)( // NOTE: type cast not necessary for int (0xff & data[0]) << 24 | (0xff & data[1]) << 16 | (0xff & data[2]) << 8 | (0xff & data[3]) << 0 ); }
public static byte[] intToByte32(int num) { byte[] arr = new byte[32]; for (int i = 31; i >= 0; i--) { // &1 也可以改為num&0x01,表示取最地位數字. arr[i] = (byte) (num & 1); // 右移一位. num >>= 1; } return arr; } public static int byte32ToInt(byte[] arr) { if (arr == null || arr.length != 32) { throw new IllegalArgumentException("byte數組必須不為空,並且長度是32!"); } int sum = 0; for (int i = 0; i < 32; ++i) { sum |= (arr[i] << (31 - i)); } return sum; }
int array to byte array
private byte[] convertIntArrayToByteArray(int[] data) { if (data == null) return null; // ---------- byte[] byts = new byte[data.length * 4]; for (int i = 0; i < data.length; i++) System.arraycopy(convertIntToByteArray(data[i]), 0, byts, i * 4, 4); return byts; }
byte array to int array
public int[] convertByteArrayToIntArray(byte[] data) { if (data == null || data.length % 4 != 0) return null; // ---------- int[] ints = new int[data.length / 4]; for (int i = 0; i < ints.length; i++) ints[i] = ( convertByteArrayToInt(new byte[] { data[(i*4)], data[(i*4)+1], data[(i*4)+2], data[(i*4)+3], } )); return ints; }
byte b1 = 65; // char ch = b1; char ch = (char) b1; System.out.println("byte value: " + b1); // prints 65 System.out.println("Converted char value: " + ch); // prints A (ASCII is 65 for A)
public static char byte2ToChar(byte[] arr) { if (arr == null || arr.length != 2) { throw new IllegalArgumentException("byte數組必須不為空,並且是2位!"); } return (char) (((char) (arr[0] << 8)) | ((char) arr[1])); } public static byte[] charToByte2(char c) { byte[] arr = new byte[2]; arr[0] = (byte) (c >> 8); arr[1] = (byte) (c & 0xff); return arr; }
public static byte[] longToByte64(long sum) { byte[] arr = new byte[64]; for (int i = 63; i >= 0; i--) { arr[i] = (byte) (sum & 1); sum >>= 1; } return arr; }
public static long byte8ToLong(byte[] arr) { if (arr == null || arr.length != 8) { throw new IllegalArgumentException("byte數組必須不為空,並且是8位!"); } return (long) (((long) (arr[0] & 0xff) << 56) | ((long) (arr[1] & 0xff) << 48) | ((long) (arr[2] & 0xff) << 40) | ((long) (arr[3] & 0xff) << 32) | ((long) (arr[4] & 0xff) << 24) | ((long) (arr[5] & 0xff) << 16) | ((long) (arr[6] & 0xff) << 8) | ((long) (arr[7] & 0xff))); } public static byte[] longToByte8(long sum) { byte[] arr = new byte[8]; arr[0] = (byte) (sum >> 56); arr[1] = (byte) (sum >> 48); arr[2] = (byte) (sum >> 40); arr[3] = (byte) (sum >> 32); arr[4] = (byte) (sum >> 24); arr[5] = (byte) (sum >> 16); arr[6] = (byte) (sum >> 8); arr[7] = (byte) (sum & 0xff); return arr; } public static long byte64ToLong(byte[] arr) { if (arr == null || arr.length != 64) { throw new IllegalArgumentException("byte數組必須不為空,並且長度是64!"); } long sum = 0L; for (int i = 0; i < 64; ++i) { sum |= ((long) arr[i] << (63 - i)); } return sum; }
public static byte[] shortToByte16(short s) { byte[] arr = new byte[16]; for (int i = 15; i >= 0; i--) { arr[i] = (byte) (s & 1); s >>= 1; } return arr; } public static short byte16ToShort(byte[] arr) { if (arr == null || arr.length != 16) { throw new IllegalArgumentException("byte數組必須不為空,並且長度為16!"); } short sum = 0; for (int i = 0; i < 16; ++i) { sum |= (arr[i] << (15 - i)); } return sum; } public static short byte2ToShort(byte[] arr) { if (arr != null && arr.length != 2) { throw new IllegalArgumentException("byte數組必須不為空,並且是2位!"); } return (short) (((short) arr[0] << 8) | ((short) arr[1] & 0xff)); } public static byte[] shortToByte2(Short s) { byte[] arr = new byte[2]; arr[0] = (byte) (s >> 8); arr[1] = (byte) (s & 0xff); return arr; }
public static double byte8ToDouble(byte[] arr) { if (arr == null || arr.length != 8) { throw new IllegalArgumentException("byte數組必須不為空,並且是8位!"); } long l = byte8ToLong(arr); return Double.longBitsToDouble(l); } public static byte[] doubleToByte8(double i) { long j = Double.doubleToLongBits(i); return longToByte8(j); }
public static float byte4ToFloat(byte[] arr) { if (arr == null || arr.length != 4) { throw new IllegalArgumentException("byte數組必須不為空,並且是4位!"); } int i = byte4ToInt(arr); return Float.intBitsToFloat(i); } public static byte[] floatToByte4(float f) { int i = Float.floatToIntBits(f); return intToByte4(i); }
byte b= -120; int a= bytes & 0xff;
byte a = (byte)234; System.out.println(a); 上面的代碼,結果是-22,因為java中byte是有符號的,byte範圍是-128~127。 如果想輸出234,該怎麼做呢,首先想到的是將a 賦給大一點的類型,如下: byte a = (byte)234; int i = a&0xff; System.out.println(i); 原因是 0xff是int,占4個位元組,a是byte,占1個位元組,進行&操作的細節如下: 00000000 00000000 00000000 11101010 (a) & 00000000 00000000 00000000 11111111 (0xff) --------------------------------------------------------------------- = 00000000 00000000 00000000 11101010 結果是int,但是符號位是0,說明是正數,最後就是正整數234.
byte bytes[] = {(byte)0, (byte)0, (byte)134, (byte)0, (byte)61}; System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(bytes));
public static String byteArrayToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(a.length * 2); for(byte b: bytes) sb.append(String.format("%02x", b)); return sb.toString(); }
BigInteger n = new BigInteger(byteArray); String hexa = n.toString(16));
byte[] one = { 1, 2, 3 }; byte[] two = { 6, 8, 9 }; int length = one.Length + two.Length; byte[] sum = new byte[length]; one.CopyTo(sum,0); two.CopyTo(sum,one.Length);
byte[] one = { 1, 2, 3 }; byte[] two = { 6, 8, 9 }; List<byte> list1 = new List<byte>(one); List<byte> list2 = new List<byte>(two); list1.AddRange(list2); byte[] sum2 = list1.ToArray();