S_a_k_Uの日記みたいなDB

~サクゥーと呼ばないで~

byte⇔int変換する

Socket通信で送受信なんかする時に、byteをintに変換したかったり、intをbyteに変換したかったり。
byte[]対応とか、符号なし対応とかしてみたり。
Javaのコードで初めてシフト演算子使ったかもw

public class ByteUtil {

  public static int toInt(byte[] bytes) {
    int i = 0;
    for ( byte b : bytes ) {
      i = ((i << 8) | (b & 0xff));
    }
    return i;
  }

  public static byte[] toByte(int val, int len) {
    byte[] b = new byte[len];
    for ( int i = len - 1 ; i >= 0 ; i-- ) {
      b[i] = (byte) val;
      val = (val >> 8);
    }
    return b;
  }

  public static int toUnsignedInt(byte b) {
    return (b & 0xff);
  }

  public static int toInt(byte b) {
    return (int) b;
  }

  @Test
  public void test() {

    // toByte(int, int) と toInt(byte[]) のテスト
    int v = 1;
    for ( int i = 0 ; i < 32 ; i++ ) {
      test(v - 1);
      test(-(v - 1));
      test(v);
      test(-v);
      v += v;
    }
    for ( int i = 0 ; i < 9 ; i++ ) {
      for ( int j = 1 ; j < 10 ; j++ ) {
        test((int) Math.pow(10, i) * j);
      }
    }

    // toByte(int, int) と toInt(byte) のテスト
    v = 1;
    for ( int i = 0 ; i < 7 ; i++ ) {
      testOneByte(v - 1);
      testOneByte(-(v - 1));
      testOneByte(v);
      testOneByte(-v);
      v += v;
    }
    testOneByte(127);
    testOneByte(-127);
    testOneByteNotEq(128);
    testOneByte(-128);
    testOneByteNotEq(255);
    testOneByteNotEq(-255);
    testOneByteNotEq(256);
    testOneByteNotEq(-256);

    // toByte(int, int) と toUnsinedInt(byte) のテスト
    Assert.assertEquals(0, toUnsignedInt(toByte(0, 1)[0]));
    v = 1;
    for ( int i = 0 ; i < 8 ; i++ ) {
      //System.out.println(v - 1);
      //System.out.println(v);
      Assert.assertEquals(v - 1, toUnsignedInt(toByte(v - 1, 1)[0]));
      Assert.assertEquals(v, toUnsignedInt(toByte(v, 1)[0]));
      v += v;
    }
    Assert.assertEquals(255, toUnsignedInt(toByte(255, 1)[0]));
    Assert.assertNotSame(256, toUnsignedInt(toByte(256, 1)[0]));

  }
  public void test(int i) {
    //System.out.println(i);
    byte[] b = toByte(i, 4);
    Assert.assertEquals(i, toInt(b));
   }
  public void testOneByte(int i) {
    //System.out.println(i);
    byte[] b = toByte(i, 1);
    Assert.assertEquals(i, toInt(b[0]));
  }
  public void testOneByteNotEq(int i) {
    //System.out.println(i);
    byte[] b = toByte(i, 1);
    Assert.assertNotSame(i, toInt(b[0]));
  }

}