如何将8字节整数转换为4字节整数

  • 本文关键字:整数 字节 转换 c++
  • 更新时间 :
  • 英文 :


我正在尝试将8字节整数转换为4字节整数,以便我可以在屏幕上绘制立方体。它给我的警告是:

警告C26451算术溢出:在4字节上使用operator '*'值,然后将结果强制转换为8字节值。将值转换为在调用operator '*'之前设置更宽的类型,以避免溢出(io.2)。somthingC: 用户Admin 回购 renderer.cpp事情事情来源79

我不能将4字节整型改为8字节整型,因为它不能与我的代码的其他部分一起工作。

这是我使用的代码,错误在第79行:

#include <Windows.h>
struct Render_State
{
int width;
int hight;
void* memory;
BITMAPINFO bitmap_info;
};
Render_State render_state;
void render_backround(HWND hwnd,int colour)
{
if (WM_PAINT)
{

PAINTSTRUCT ps;

HDC hdc = BeginPaint(hwnd, &ps);
unsigned int* pixel = (unsigned int*)render_state.memory;
for (int y = 0; y < render_state.hight; y+=1)
{
for (int x = 0; x < render_state.width; x+=1)
{
*pixel++ = colour;

}
}
// render
StretchDIBits(
hdc, 0, 0, render_state.width, render_state.hight, 0, 0, render_state.width, render_state.hight,
render_state.memory, &render_state.bitmap_info, DIB_RGB_COLORS, SRCCOPY); {}
EndPaint(hwnd, &ps);
}
}
void clear_screen(HWND hwnd, int colour)
{
if (WM_PAINT)
{
PAINTSTRUCT ps;

HDC hdc = BeginPaint(hwnd, &ps);
unsigned int* pixel = (unsigned int*)render_state.memory;
for (int y = 0; y < render_state.hight; y += 1)
{
for (int x = 0; x < render_state.width; x += 1)
{
*pixel++ = colour;
}
}
// render

StretchDIBits(hdc,0,0,render_state.width,render_state.hight,
0,0,render_state.width,render_state.hight,
render_state.memory, &render_state.bitmap_info, DIB_RGB_COLORS, SRCCOPY); {}
EndPaint(hwnd, &ps);
}
}
void draw_rect(HWND hwnd, int X, int Y, int X2 , int Y2, int colour)
{
if (WM_PAINT)
{
PAINTSTRUCT ps;

HDC hdc = BeginPaint(hwnd, &ps);

for (int  y = Y; y <Y2; y += 1)
{
// line 79 
unsigned int* pixel = (unsigned int*)render_state.memory + X + y * render_state.width;

for (int x = X; x < X; x += 1)
{
*pixel++ = colour;
}
}
// render
StretchDIBits(hdc, 0, 0, render_state.width, render_state.hight, 0, 0, 
render_state.width, render_state.hight,
render_state.memory, &render_state.bitmap_info, DIB_RGB_COLORS, SRCCOPY); {}
EndPaint(hwnd, &ps);
}
}

您所指的bit实际上是byte。原因是在c++中编程时,您使用的最小内存大小是一个字节(可能会有所不同)。所以不是4 bit8 bit,而是4 bytes8 bytes

unsigned int*可以在x64应用程序中表示为一个8字节的整数。在这些类型的应用程序中,int的大小通常为4字节。编译器说的是"既然你稍后将其转换为8字节值,为什么不先将其转换为8字节值,然后将其相乘?"这是为了确保不会有任何算术溢出(该值对于int类型来说太大了)。

要解决这个问题,您所需要做的就是将y转换为8字节。而且,由于您无论如何将其转换为unsigned8字节值,您可以使用size_t,或者更准确地说,使用uint64_t(包括"inttypes")或";cstdint"),我建议使用static_cast

例子:
下面的代码会给你同样的警告:

// x64 build.
int main()
{
int x = 25;
size_t y = x * x;    // <-- 
}

要解决这个问题,我们只需要将x强制转换为size_t

int main()
{
int x = 25;
size_t y = static_cast<size_t>(x) * x;    // <-- 
// Casting one "x" will be enough as the size will automatically resolve to 8 bytes.
}

最新更新