博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java各个类型与byte[]的转换

Posted on 2012-07-05 16:05  Wuqh  阅读(530)  评论(0编辑  收藏  举报

short 转byte[]

 int temp = val;
  byte[] bt=new byte[2];
  for (int i = 0; i < 2; i++)
  {
     bt[i]=new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位
     temp = temp >> 8; // 向右移8位
  }

int 转byte[]

  int temp = v;
  byte[] bt = new byte[4];
  for (int i = 0; i < bt.length; i++)
  {
   bt[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位
   temp = temp >> 8; // 向右移8位
  }

long 转byte[]

  long temp = v;
  byte writeBuffer[] = new byte[8];
  for (int i = 0; i < writeBuffer.length; i++)
  {
   writeBuffer[i] = new Long(temp & 0xff).byteValue();   // 将最低位保存在最低位
   temp = temp >> 8;   // 向右移8位
  }

String 转byte[]

String s=new String("测试");

byte[] wrbyte = s.getBytes();

 byte[]转short

 int reval1 = 0;
  int reval2 = 0;
  int reval3 = 0;
  int reval4 = 0;
  try
  {
     reval1 = stream.read();
     reval2 = stream.read();
     reval3 = stream.read();
     reval4 = stream.read();
  } catch (IOException e)
  {
   // TODO Auto-generated catch block
     e.printStackTrace();
  }

int returnval=(reval1) | (reval2 << 8) ;

 

 

byte[]转int

 

  int reval1 = 0;
  int reval2 = 0;
  int reval3 = 0;
  int reval4 = 0;
  try
  {
     reval1 = stream.read();
     reval2 = stream.read();
     reval3 = stream.read();
     reval4 = stream.read();
  } catch (IOException e)
  {
   // TODO Auto-generated catch block
     e.printStackTrace();
  }

int returnval=(reval1) | (reval2 << 8) | (reval3 << 16) |(reval4 << 24);
 byte[]转long

 

  int reval1 = 0;
  int reval2 = 0;
  int reval3 = 0;
  int reval4 = 0;
  try
  {
     reval1 = stream.read();
     reval2 = stream.read();
     reval3 = stream.read();
     reval4 = stream.read();
  } catch (IOException e)
  {
   // TODO Auto-generated catch block
     e.printStackTrace();
  }

 

int returnval=(reval1) | (reval2 << 8) | (reval3 << 16) |(reval4 << 24)|(reval4 << 32)|(reval4 << 48)|(reval4 << 64)|(reval4 << 72);;

 

byte[]转String