我正在尝试将 8 字节整数转换为 4 字节整数,以便我可以在屏幕上绘制一个立方体。 它给我的警告是:
<块引用>警告 C26451 算术溢出:在 4 字节上使用 operator '*'
值,然后将结果转换为 8 字节值。将值转换为
调用 operator '*'
之前的更广泛的类型以避免溢出
(io.2)。 somthingC:\Users\Admin\source\repos\somthing\somthing\renderer.cpp 79
我无法将 4 字节 int 更改为 8 字节 int,因为它不适用于我代码的其他部分。
这是我使用的代码,错误在第 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);
}
}
答案 0 :(得分:3)
您所指的 bit
实际上是一个 byte
。原因是在用 C++ 编程时,您使用的最小内存大小是一个字节(它可能会有所不同)。所以它不是 4 bit
或 8 bit
,它实际上是 4 bytes
和 8 bytes
。
unsigned int*
在 x64
应用程序中可以表示为 8 字节整数。在这些类型的应用程序中,int
的大小通常为 4 个字节。编译器所说的是“既然你后来将它转换为一个 8 字节的值,为什么不先将它转换为一个 8 字节的值,然后再乘以它呢?”。这是为了确保不会出现任何算术溢出(该值太大,int
类型无法容纳)。
要解决此问题,您只需将 y
转换为 8 个字节。并且由于您无论如何都将其转换为 unsigned
8 字节值,因此您可以使用 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.
}