byte toPositiveInt method

余生长醉 提交于 2019-12-11 15:45:14

问题


is there anything like this in JDK or Apache Commons (or in other jar)?

/**
 * Return the integer positive value of the byte. (e.g. -128 will return
 * 128; -127 will return 129; -126 will return 130...)
 */
public static int toPositiveInt(byte b) {
int intV = b;
 if (intV < 0) {
     intV = -intV;
     int diff = ((Byte.MAX_VALUE + 1) - intV) + 1;
     intV = Byte.MAX_VALUE + diff;
 }
 return intV;
    }

回答1:


Usually, you use some basic bit manipulation for this:

public static int toPositiveInt(byte b) {
return b & 0xFF;
}

And because it is so short, it is usually inlined and not called as a method.



来源:https://stackoverflow.com/questions/2640946/byte-topositiveint-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!