byte[]/char* 转int, int 转byte[]/char 大小端

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wuchuanpingstone/article/details/80321676
/**
 * 以大端模式将int转成byte[]/char
 */
public static byte[] intToBytesBig(int value) {
    byte[] src = new byte[4];
    src[0] = (byte) ((value >> 24) & 0xFF);
    src[1] = (byte) ((value >> 16) & 0xFF);
    src[2] = (byte) ((value >> 8) & 0xFF);
    src[3] = (byte) (value & 0xFF);
    return src;
}

public static char* intToCharBig(int value) {
    char src[4];
    src[0] = (char) ((value >> 24) & 0xFF);
    src[1] = (char) ((value >> 16) & 0xFF);
    src[2] = (char) ((value >> 8) & 0xFF);
    src[3] = (char) (value & 0xFF);
    return src;
}


/**
 * 以小端模式将int转成byte[]/char
 *
 * @param value
 * @return
 */
public static byte[] intToBytesLittle(int value) {
    byte[] src = new byte[4];
    src[3] = (byte) ((value >> 24) & 0xFF);
    src[2] = (byte) ((value >> 16) & 0xFF);
    src[1] = (byte) ((value >> 8) & 0xFF);
    src[0] = (byte) (value & 0xFF);
    return src;
}

public static char* intToCharBig(int value) {
    char src[4];
    src[3] = (char) ((value >> 24) & 0xFF);
    src[2] = (char) ((value >> 16) & 0xFF);
    src[1] = (char) ((value >> 8) & 0xFF);
    src[0] = (char) (value & 0xFF);
    
    return src;
}


/**
 * 以大端模式将byte[]/char转成int
 */
public static int bytesToIntBig(byte[] src, int offset) {
    int value;
    value = (int) (((src[offset] & 0xFF) << 24)
            | ((src[offset + 1] & 0xFF) << 16)
            | ((src[offset + 2] & 0xFF) << 8)
            | (src[offset + 3] & 0xFF));
    return value;
}

public static int charToIntBig(char* src, int offset){
    int value;
    value = (int) (((src[offset] & 0xFF) << 24)
            | ((src[offset + 1] & 0xFF) << 16)
            | ((src[offset + 2] & 0xFF) << 8)
            | (src[offset + 3] & 0xFF));
    return value;
}
/**
 * 以小端模式将byte[]/char转成int
 */
public static int bytesToIntLittle(byte[] src, int offset) {
    int value;
    value = (int) ((src[offset] & 0xFF)
            | ((src[offset + 1] & 0xFF) << 8)
            | ((src[offset + 2] & 0xFF) << 16)
            | ((src[offset + 3] & 0xFF) << 24));
    return value;
}

public static int charToIntLittle(char* src, int offset) {
    int value;
    value = (int) ((src[offset] & 0xFF)
            | ((src[offset + 1] & 0xFF) << 8)
            | ((src[offset + 2] & 0xFF) << 16)
            | ((src[offset + 3] & 0xFF) << 24));
    return value;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页