Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // byte配列(10進数文字列)から数値を取得
- public class Test
- {
- /**
- * byte配列(10進数文字列)から数値を取得
- * <p>
- * 特別にパフォーマンスを要求する場合を除いて、
- * Integer.parseInt(new String(...)) を使うことを推奨します。
- * </p>
- * @param bArray 文字列が格納された配列
- * @param startIndex 読み取り開始インデックス
- * @return 取得した数値
- */
- public static int parseIntFromBytes(byte[] bArray, int startIndex)
- {
- long number = 0;
- boolean signed = false;
- // 符号を取得
- if (bArray.length > 0)
- {
- if (bArray[startIndex] == '-')
- {
- signed = true;
- startIndex++;
- }
- else if (bArray[startIndex] == '+')
- {
- startIndex++;
- }
- }
- // 整数値を取得
- for (int i = startIndex; i < bArray.length; i++)
- {
- byte c = bArray[i];
- if (c >= '0' && c <= '9')
- {
- number *= 10;
- number += (c - '0');
- if (number > ((long)Integer.MAX_VALUE + (signed ? 1 : 0)))
- {
- throw new ArithmeticException("Arithmetic overflow. Number too large.");
- }
- }
- else if (c == 0 || c == '\r' || c == '\n')
- {
- break;
- }
- else
- {
- throw new NumberFormatException("For character 0x" + String.format("%02x", c & 0xff) + ".");
- }
- }
- // 負数であれば符号を反転
- if (signed)
- {
- number = -number;
- }
- return (int)number;
- }
- // テスト
- public static void main(String[] args)
- {
- try
- {
- if (args.length == 0)
- {
- System.out.println("Give me a number.");
- return;
- }
- final int repeatCount = 5 * 1024 * 1024;
- byte[] bytes = args[0].getBytes();
- long tickStart, tickEnd;
- long dummy = 0;
- // parseIntFromBytes
- System.out.println("parseIntFromBytes start");
- tickStart = System.currentTimeMillis();
- for (int i = 0; i < repeatCount; i++)
- {
- dummy += parseIntFromBytes(bytes, 0);
- }
- tickEnd = System.currentTimeMillis();
- System.out.println("parseIntFromBytes end [" + (tickEnd - tickStart) + " ms]");
- // parseInt
- System.out.println("parseInt start");
- tickStart = System.currentTimeMillis();
- for (int i = 0; i < repeatCount; i++)
- {
- dummy += Integer.parseInt(new String(bytes));
- }
- tickEnd = System.currentTimeMillis();
- System.out.println("parseInt end [" + (tickEnd - tickStart) + " ms]");
- // 未使用変数扱いされたくないので出力
- System.out.println(dummy);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
Add Comment
Please, Sign In to add comment