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


原文鏈接:http://blog.csdn.net/puttytree/article/details/7825709

NumberUtil.h

//
//  NumberUtil.h
//  MinaCppClient
//
//  Created by yang3wei on 7/22/13.
//  Copyright (c) 2013 yang3wei. All rights reserved.
//

#ifndef __MinaCppClient__NumberUtil__
#define __MinaCppClient__NumberUtil__

#include <string>

/**
 * htonl 表示 host to network long ,用於將主機 unsigned int 型數據轉換成網絡字節順序;
 * htons 表示 host to network short ,用於將主機 unsigned short 型數據轉換成網絡字節順序;
 * ntohl、ntohs 的功能分別與 htonl、htons 相反。
 */

/**
 * byte 不是一種新類型,在 C++ 中 byte 被定義的是 unsigned char 類型;
 * 但在 C# 里面 byte 被定義的是 unsigned int 類型
 */
typedef unsigned char byte;

/**
 * int 轉 byte
 * 方法無返回的優點:做內存管理清爽整潔
 * 如果返回值為 int,float,long,double 等簡單類型的話,直接返回即可
 * 總的來說,這真心是一種很優秀的方法設計模式
 */
void int2bytes(int i, byte* bytes, int size = 4);

// byte 轉 int
int bytes2int(byte* bytes, int size = 4);

#endif /* defined(__MinaCppClient__NumberUtil__) */

NumberUtil.cpp

//
//  NumberUtil.cpp
//  MinaCppClient
//
//  Created by yang3wei on 7/22/13.
//  Copyright (c) 2013 yang3wei. All rights reserved.
//

#include "NumberUtil.h"

void int2bytes(int i, byte* bytes, int size) {
    // byte[] bytes = new byte[4];
    memset(bytes,0,sizeof(byte) *  size);
    bytes[0] = (byte) (0xff & i);
    bytes[1] = (byte) ((0xff00 & i) >> 8);
    bytes[2] = (byte) ((0xff0000 & i) >> 16);
    bytes[3] = (byte) ((0xff000000 & i) >> 24);
}

int bytes2int(byte* bytes, int size) {
    int iRetVal = bytes[0] & 0xFF;
    iRetVal |= ((bytes[1] << 8) & 0xFF00);
    iRetVal |= ((bytes[2] << 16) & 0xFF0000);
    iRetVal |= ((bytes[3] << 24) & 0xFF000000);
    return iRetVal;
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM