1. 程式人生 > >C++: byte 和 int 的相互轉化

C++: byte 和 int 的相互轉化

typedef unsigned char bt;
typedef unsigned int ui;

void ui2bts(bt* out_pBts, ui in_uiLen) {
    if (!out_pBts) {
        printf("NULL == out_pBts\n");
        return;
    }
    out_pBts[0] = (bt)(in_uiLen & 0xff);
    out_pBts[1] = (bt)((in_uiLen >> 8) & 0xff);
    out_pBts[2] = (bt)((in_uiLen >> 16) & 0xff);
    out_pBts[3] = (bt)((in_uiLen >> 24) & 0xff);
}

ui bts2ui(bt* in_pBts) {
    if (!in_pBts) {
        printf("NULL == in_pBts\n");
        return 0;
    }
    ui t_uiResult = (ui)in_pBts[0] & 0xff;
    t_uiResult |= (((ui)in_pBts[1] << 8) & 0xff00);
    t_uiResult |= (((ui)in_pBts[2] << 16) & 0xff0000);
    t_uiResult |= (((ui)in_pBts[3] << 24) & 0xff000000);
    return t_uiResult;
}