如何将二进制代码转换为灰度图像?含恶意代码转换场景
Hey there! Let me walk you through exactly how to convert malicious binary code into grayscale images—this is a useful visualization technique for malware analysis, since it can reveal structural patterns in the code that might not be obvious from raw bytes.
I’ll use Python for the examples here, since it’s the most accessible tool for this task, but the core logic applies to any language.
1. Read the Malware Binary Data
First, you need to load the raw binary content of the malicious file. Each byte in this file will map directly to a grayscale pixel value later.
# Open the malware binary file in read-binary mode with open("malware_sample.bin", "rb") as f: binary_data = f.read() # This returns a bytes object containing all raw bytes
2. Convert Binary Data to an 8-bit Value Vector
Every byte in the binary data is already an 8-bit value (ranging from 0x00 to 0xFF, which translates to 0 to 255 in decimal). We just need to convert this bytes object into a list of integers, where each integer represents a grayscale pixel intensity (0 = black, 255 = white).
# Convert each byte in the binary data to its integer equivalent pixel_values = [byte for byte in binary_data]
3. Reshape the 1D Vector into a 2D Image Matrix
Images are 2D, so we need to turn our 1D list of pixel values into a 2D grid. The goal is to find a width and height that’s as close to square as possible (for better visualization).
import math import numpy as np total_pixels = len(pixel_values) # Calculate the closest integer square root for the width width = math.ceil(math.sqrt(total_pixels)) # Calculate the required height to fit all pixels height = math.ceil(total_pixels / width) # If the total pixels don't perfectly fill the width×height grid, pad with 0s (black pixels) pixel_values += [0] * (width * height - total_pixels) # Reshape the 1D list into a 2D numpy array (height × width) image_matrix = np.array(pixel_values).reshape((height, width))
4. Generate and Save the Grayscale Image
Finally, we’ll convert the 2D matrix into an actual grayscale image using a library like PIL (Pillow) or OpenCV. Here’s how to do it with Pillow:
from PIL import Image # Create a grayscale image from the matrix (mode 'L' = 8-bit grayscale) grayscale_img = Image.fromarray(image_matrix.astype('uint8'), mode='L') # Save the image to disk grayscale_img.save("malware_visualization.png") # Or display it directly grayscale_img.show()
- Why 8-bit vectors? Each byte in binary code is exactly 8 bits, so mapping each byte to an 8-bit grayscale value is a direct, lossless conversion—no information is lost in the process.
- Pattern Recognition: Malware often has repeating byte sequences or distinct structural blocks that show up as unique textures in the grayscale image. This can help analysts quickly identify similarities between different malware samples.
内容的提问来源于stack exchange,提问作者Lelouch

