public class Util Reverse 反转 整数、字节
package com.newglobal.dispense.util;
public class Util {
//按字节反转
public static int reverseB(int num){
int ret = 0;
String str = "" + num;//0123456789L
int len = str.length()%2 + 1;
byte[] bt = str.getBytes();
for (int i = 0; i < 16 ; i++){
ret |= (num & (1 << i)) << (31-2*i);//先找到低2位,然后移动到对应的高2位,再与要返回的结果 或
System.out.println(num);
System.out.println(num & (1 << i));
//System.out.println(ret);
ret |= (num & (0x80000000 >> i*2) ) >> (31-2*i);//再找到高2位,然后移动到对应的低2位,再与要返回的结果 或
}
return ret;
}
//按字节反转
public static int reverseByte(int num){
int ret = 0;
ret += num << 24;
ret += ((num << 16 | 0xFFFFFF) >> 24) * 0x10000;
ret += ((num << 8 | 0xFFFFFF) >> 24) * 0x100;
ret += (num | 0xFFFFFF) >> 24;
return ret;
}
// 按字节反转
public static short reverseShort(short num){
short ret = 0;
ret += num << 8;
System.out.println("ret1="+ret);
ret += (num | 0xFF) >> 8;
System.out.println("ret2="+ret);
return ret;
}
//按字节反转一个int整数
public static int reverseInt(int num){
int ret = 0;
ret += ((num << 24) & 0xFF) * 0x1000000;
ret += ((num << 16) & 0xFF) * 0x10000;
ret += ((num << 8 ) & 0xFF) * 0x100;
ret += (num & 0xFF);
return ret;
}
public static void main(String[] args) {
int ii = 0x12345678;//7ffffffe;//2147483646;
int nn = reverseByte(ii);
short ss = 0x3827;
short mm = reverseShort(ss);
int i = reverseInt(ii);
System.out.println("reverseShort="+mm);
System.out.println("reverseInt="+i);
}
//按字节反转一个int整数
/*public int reverseInt(int num){
int ret = 0;
ret += num << 24;
ret += ((num << 16 | 0xFFFFFF) >> 24) * 0xFFFF;
ret += ((num << 8 | 0xFFFFFF) >> 24) * 0xFF;
ret += (num | 0xFFFFFF) >> 24;
return ret;
}*/
}
浙公网安备 33010602011771号