关于 byte 转化为 int 的疑问

来源:百度知道 编辑:UC知道 时间:2024/05/21 01:55:39
int readInt(ifstream &input) {
char buffer[4];
input.read(buffer, 4);
return toInt(buffer); //从文件流中读取4个byte
} //已知是 little endian

int toInt(const char* bytes) {
return (int)(((unsigned char)bytes[3] << 24) |
((unsigned char)bytes[2] << 16) |
((unsigned char)bytes[1] << 8) |
(unsigned char)bytes[0]);
}

这样readInt 函数就能从 文件流头上读出 4个byte 并转化为int

问题是 toInt中 bytes[1],bytes[2]等等不都是一个byte的长度吗,它left shift 8位 16位 不都变成0了吗 怎么达到提高 bytes[1] bytes[2]
bytes[3] 介数的目的的?
toInt 是在 readInt前的,打错了

关键请解释一下 bitwise operator : bytes[3]<<24 为什么可以这样使用

bytes[3] 本身不是 1一个 字节的长度吗? 向左shift 24位 不成了0了吗?

程序没错,我用它来读bmp 文件的 宽 和 高 都是正确的

bytes[3]<<24 这样子是你说的那样
我想是因为函数是返回 int型
等于先把每个都强制转化成int型 再 “|”运算
我试验了下 是与 "|" 有关

char a = 10;
char b = 20;

int c;

c = a<<10 | b<<10 ;
或者 c = a<<10 + b<<10 2种情况你试下估计就了解了

int readInt(ifstream &input) {
unsigned char buffer[4];
input.read(buffer, 4);
return toInt(buffer); //从文件流中读取4个byte
} //已知是 little endian

int toInt(const unsinged char* bytes) {
return (int)(((int)bytes[3] << 24) |
((int)bytes[2] << 16) |
((int)bytes[1] << 8) |
(int)bytes[0]);
}

我用的办法:
int readInt(ifstream &input) {
int n;
input.read(&n, 4);
return n;
}

或者:
int toInt(const unsigned char* bytes) {
return *((int*)bytes);
}

一个字节左移8位。。。肯定溢出了啊