---
title: "byte[]和int间的转换"
author: "klts"
date: "2012-01-17T17:22:08Z"
tags: []
categories: ["编程语言"]
slug: "byte-int"
draft: false
lastmod: "2012-01-17T17:22:56Z"
id: 1354561
url: "https://klts.iteye.com/blog/1354561"
---

```
  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; 
  } 
```