ITeye博客

byte[]和int间的转换

klts · 2012-01-17 17:22 · 代码 · 编程语言 · Markdown

  public static byte[] i2b(int i) {
    byte[] bt = new byte[4];
    bt[3] = (byte) (0xff & i);
    bt[2] = (byte) ((0xff00 & i) >> 8);
    bt[1] = (byte) ((0xff0000 & i) >> 16);
    bt[0] = (byte) ((0xff000000 & i) >> 24);
    return bt;
  }
  
  private static int toInt(byte b){ 
    if(b >= 0) return (int)b; 
    else return (int) (b + 256); 
  } 

  private static int b2i(byte[] byteValue){ 
    if(byteValue.length != 4) 
      return 0; 
    int intValue = 0; 
    try{ 
      intValue = toInt(byteValue[0]); 
      intValue = (intValue << 8) + toInt(byteValue[1]); 
      intValue = (intValue << 8) + toInt(byteValue[2]); 
      intValue = (intValue << 8) + toInt(byteValue[3]); 
    } 
    catch(Exception e){ 
      e.printStackTrace(); 
    } 
    return intValue; 
  } 

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。