我试图使我的项目python2.7和3兼容,而python 3有内置方法int.from_bytes。 python 2.7中是否存在等价物,或者说这个代码2.7和3兼容的最佳方法是什么?
>>> int.from_bytes(b"f483", byteorder="big")
1714698291
答案 0 :(得分:21)
您可以将其视为编码(特定于Python 2):
>>> int('f483'.encode('hex'), 16)
1714698291
或者在Python 2和Python 3中:
>>> int(codecs.encode(b'f483', 'hex'), 16)
1714698291
优点是字符串不限于特定大小的假设。缺点是它是未签名的。
答案 1 :(得分:6)
struct.unpack(">i","f483")[0]
可能?
>
表示big-endian,i
表示签名32位int
答案 2 :(得分:4)
使用struct
模块将字节解压缩为整数。
//StudentMain.cpp
#include <iostream>
#include <iomanip>
#include "Students.h"
#include "Students.cpp"
using namespace std;
int main()
{
Students Students();//("sue", "Jones", "3.2");
cout << "Employee Info obtained by get functions: \n"
<< "\nFirst name is: " << _Students.getFirstName()
<< "\nLast Name is: " << Students.getLastName()
<< "\nGPA is: " << Students.GPA() << endl;
cout << "\n updated information\n" << endl;
Students.print();
return 0;
}
//Students.h
#ifndef COMMISSION_H
#define COMMISION_H
#include <string>
class Students
{
public:
Students(const std::string &, const std::string &, float = 0.0);
void setFirstName(const std::string &);
std::string getFirstName() const;
void setLastName(const std::string &);
std::string getLastName() const;
void setGPA(float);
float getGPA() const;
void print() const;
//std::string firstName;
//std::string lastName;
//float gpa;
private:
std::string firstName;
std::string lastName;
float gpa;
};
#endif
//Students.cpp
#include <iostream>
#include <stdexcept>
#include "Students.h"
#include <cmath>
using namespace std;
Students::Students(const string &first, const string &last, float gpa)
{
firstName = first;
lastName = last;
setGPA(gpa);
}
void Students::setFirstName(const string & first)
{
firstName = first;
}
string Students::getFirstName() const
{
return firstName;
}
void Students::setLastName(const string &last)
{
lastName = last;
}
string Students::getLastName() const
{
return lastName;
}
void Students::setGPA(float gpa)
{
if (gpa < 4.1)
throw invalid_argument("GPA must be set below 4.0");
}
float Students::getGPA() const
{
return gpa;
}
void Students::print() const
{
cout << "Students Information:\t " << firstName << ' ' << lastName
<< "\n GPA:" << gpa;
}
答案 3 :(得分:0)
> import binascii
> barray = bytearray([0xAB, 0xCD, 0xEF])
> n = int(binascii.hexlify(barray), 16)
> print("0x%02X" % n)
0xABCDEF