所以我目前正在使用 ncurses 和 Ubuntu 系统文件来实现 top 命令,我一直想知道它显示的任务到底是什么。
我确实明白它们是设备上运行的进程,但我正在寻找 Ubuntu 文件夹,在那里我可以看到总任务数或正在运行的不同任务。
所以我目前正在使用 ncurses 和 Ubuntu 系统文件来实现 top 命令,我一直想知道它显示的任务到底是什么。
我确实明白它们是设备上运行的进程,但我正在寻找 Ubuntu 文件夹,在那里我可以看到总任务数或正在运行的不同任务。
我是 C 编程新手。我正在尝试将 C 结构写入文件并将其读回。我正在使用 valgrind 检查内存泄漏和潜在错误。当我运行程序时,我收到一组 valgrind 错误,但没有内存泄漏。该程序还准确地将数据写入文件并从文件中读回数据。我创建了一个单独的测试程序 ( testRead
) 来测试在运行用于写入文件的测试程序 ( testUsers
) 后读回文件,并且数据被正确读回。我还可以使用 hexdump 验证磁盘上的数据是否正确。valgrind 错误是什么意思 - 错误消息中引用的未启动字节是什么?
运行返回的错误:valgrind -s --track-origins=yes --leak-check=full --show-leak-kinds=all ./testUsers
==1155442== HEAP SUMMARY:
==1155442== in use at exit: 0 bytes in 0 blocks
==1155442== total heap usage: 11 allocs, 11 frees, 10,448 bytes allocated
==1155442==
==1155442== All heap blocks were freed -- no leaks are possible
==1155442==
==1155442== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==1155442==
==1155442== 1 errors in context 1 of 1:
==1155442== Syscall param write(buf) points to uninitialised byte(s)
==1155442== at 0x4989887: write (write.c:26)
==1155442== by 0x48FFEEC: _IO_file_write@@GLIBC_2.2.5 (fileops.c:1180)
==1155442== by 0x49019E0: new_do_write (fileops.c:448)
==1155442== by 0x49019E0: _IO_new_do_write (fileops.c:425)
==1155442== by 0x49019E0: _IO_do_write@@GLIBC_2.2.5 (fileops.c:422)
==1155442== by 0x4900FD7: _IO_file_close_it@@GLIBC_2.2.5 (fileops.c:135)
==1155442== by 0x48F3D8E: fclose@@GLIBC_2.2.5 (iofclose.c:53)
==1155442== by 0x10991E: saveToFile (in /home/mark/ESP32-Projects/esp32-launcher/sandbox/users-binary_save/testUsers)
==1155442== by 0x109D0E: main (in /home/mark/ESP32-Projects/esp32-launcher/sandbox/users-binary_save/testUsers)
==1155442== Address 0x4aa17f6 is 6 bytes inside a block of size 4,096 alloc'd
==1155442== at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==1155442== by 0x48F3BA3: _IO_file_doallocate (filedoalloc.c:101)
==1155442== by 0x4902CDF: _IO_doallocbuf (genops.c:347)
==1155442== by 0x4901F5F: _IO_file_overflow@@GLIBC_2.2.5 (fileops.c:744)
==1155442== by 0x49006D4: _IO_new_file_xsputn (fileops.c:1243)
==1155442== by 0x49006D4: _IO_file_xsputn@@GLIBC_2.2.5 (fileops.c:1196)
==1155442== by 0x48F4FD6: fwrite (iofwrite.c:39)
==1155442== by 0x1098A5: saveToFile (in /home/mark/ESP32-Projects/esp32-launcher/sandbox/users-binary_save/testUsers)
==1155442== by 0x109D0E: main (in /home/mark/ESP32-Projects/esp32-launcher/sandbox/users-binary_save/testUsers)
==1155442== Uninitialised value was created by a heap allocation
==1155442== at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==1155442== by 0x1095F6: findUser (in /home/mark/ESP32-Projects/esp32-launcher/sandbox/users-binary_save/testUsers)
==1155442== by 0x1094F4: createUser (in /home/mark/ESP32-Projects/esp32-launcher/sandbox/users-binary_save/testUsers)
==1155442== by 0x1093DE: initDB (in /home/mark/ESP32-Projects/esp32-launcher/sandbox/users-binary_save/testUsers)
==1155442== by 0x109AFF: main (in /home/mark/ESP32-Projects/esp32-launcher/sandbox/users-binary_save/testUsers)
用户.h
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_USERS 3
#define MAX_USER_NAME_SIZE 20
#define PERMISSION_LAUNCH 4
#define PERMISSION_EDIT_USER 2
#define PERMISSION_EDIT_LAUNCHER 1
typedef struct {
char user_name[20];
char password[20];
int permissions;
int index;
} User;
typedef struct {
int code;
char *message;
char* payload;
} Error;
extern char* user_names[MAX_USERS][MAX_USER_NAME_SIZE];
Error create_error(int code, char *message);
Error createUser(char* user_name, char* password, int permissions);
User* findUser(char * user_name);
void printUsers();
Error initDB();
void deleteUsers();
Error saveToFile();
Error readFromFile();
用户.c
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "users.h"
/* An array of pointers to the User structs created */
static User* users_storage[MAX_USERS];
/* The number of users in the users_storage array */
int user_counter = 0;
/* File name for saving the users_storage to disk */
const char* USER_FILE_NAME = "users.dat";
/*
A struct to return error messages to the UI as needed for errors that come up.
There are no different error codes, just 0 for success and -1 for an error. The UI
Would check the error code and then display the error message.
*/
Error create_error(int code, char *message) {
Error err;
err.code = code;
err.message = message;
err.payload = "Nothing to see here.";
return err;
}
/*
Null out the users_storage and add the "admin" user to the users_storage
*/
Error initDB() {
Error result = create_error(0, "Success");
for (int i = 0; i < MAX_USERS; i++) {
if (users_storage[i] != NULL) {
free(users_storage[i]);
}
users_storage[i] = NULL;
}
int permissions = PERMISSION_LAUNCH + PERMISSION_EDIT_USER + PERMISSION_EDIT_LAUNCHER;
result = createUser("admin", "password", permissions);
return result;
}
/*
Create a new User.
- Checks for invalid permissions; it must be between 1 and 7
- Checks for duplicate users using the user name
- Creates a new user and adds it to the users_storage
- Increments the user_counter
- If the users_storage is full (ie there are MAX_USERS in the users_storage), then an error is returned
with a message for the UI that a user must be deleted before a new one can be created.
*/
Error createUser(char* user_name, char* password, int permissions) {
int user_permissions = 0;
Error result = create_error(0, "Success");
if (permissions < 0 || permissions > 7) {
result.code = -1;
result.message = "Invalid permissions. Permissions must be between 0 and 7. Permissions set to 1.";
user_permissions = 1;
}
else {
user_permissions = permissions;
}
User* duplicate = findUser(user_name);
if (duplicate != NULL) {
result.message = "Duplicate user";
result.code = -1;
return result;
}
User* user = findUser(NULL);
if (user != NULL) {
strcpy(user->user_name, user_name);
strcpy(user->password, password);
user->permissions = user_permissions;
user_counter++;
return result;
}
else {
result.message = "Out of user memory. Delete a user before creating another one.";
result.code = -1;
return result;
}
}
/*
Finds a user by user name.
- Returns NULL if the user does not exist
- Returns the User struct if the user is found
*/
User* findUser(char* user_name) {
for (int i = 0; i < MAX_USERS; i++) {
User * user = users_storage[i];
if (user == NULL && user_name == NULL) {
// found and empty user slot
User * user = malloc(sizeof(User));
user->index = i;
users_storage[i] = user;
return user;
}
if (user != NULL && user_name != NULL) {
if (strcmp(user->user_name, user_name) == 0) {
return user;
}
}
}
return NULL;
}
/*
Convenience function to print out the contents of the users_storage in a human
readable format for debugging.
*/
void printUsers() {
for (int i = 0; i < MAX_USERS; i++) {
User* user = users_storage[i];
if (user != NULL) {
printf("%i, %s, %s, %i, %i\n", i, user->user_name, user->password, user->permissions, user->index);
}
else {
printf("%i, NULL\n", i);
}
}
}
/*
Used by readFromFile to clear the users_storage.
*/
void deleteUsers() {
for (int i=0; i<MAX_USERS; i++) {
if (users_storage[i] != NULL) {
User* user = users_storage[i];
printf("deleteUsers user_name=%s\n", user->user_name);
free(user);
users_storage[i] = NULL;
}
}
}
/*
Write the users_storage to a binary file
*/
Error saveToFile() {
Error result = create_error(0, "Success");
FILE *file = fopen(USER_FILE_NAME, "wb");
if (file == NULL) {
result.message = "Error opening file";
result.code = -1;
return result;
}
size_t element_count = 0;
for (int i = 0; i < MAX_USERS; i++) {
if (users_storage[i] != NULL) {
User* user = users_storage[i];
//printf("user_name=%s, password=%s, permissions=%i, index=%i\n", user->user_name, user->password, user->permissions, user->index);
fwrite(user, sizeof(User), 1, file);
if (ferror(file)) {
perror("Error writing to file");
result.message = "Error writing to file";
result.code = -1;
fclose(file);
return result;
}
element_count++;
}
}
fclose(file);
result.payload = "User data saved in a file";
return result;
}
/*
Read the users_storage from a binary file
*/
Error readFromFile() {
Error result = create_error(0, "Success");
FILE *file = fopen(USER_FILE_NAME, "rb");
if (file == NULL) {
result.message = "Error opening file";
result.code = -1;
return result;
}
User user;
deleteUsers();
size_t read_size;
int i = 0;
int users_created = 0;
while(1) {
read_size = fread(&user, sizeof(User), 1, file);
if (read_size == 0) {
break;
}
else {
createUser(user.user_name, user.password, user.permissions);
i++;
users_created++;
}
}
fclose(file);
result.payload = "User data read from file.";
return result;
}
测试用户.c
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "users.h"
int main() {
printf("InitDB: ");
Error result = initDB();
printf("%i, %s\n",result.code, result.message);
printUsers();
//create a user with bad permissions
printf("\ncreate a user ron with bad permissions (9): ");
result = createUser("ron", "password", 9);
printf("%i, %s\n",result.code, result.message);
printUsers();
// create a user
printf("\ncreate john: ");
result = createUser("john", "pw0", 4);
printf("%i, %s\n",result.code, result.message);
printUsers();
// create the same user again
printf("\ncreate john: ");
result = createUser("john", "pw0", 4);
printf("%i, %s\n",result.code, result.message);
printUsers();
// create another user when out of users
// Need to set MAX_USERS to 4 to trip this error condition
printf("\ncreate mark: ");
result = createUser("mark", "pw0", 4);
printf("%i, %s\n",result.code, result.message);
printUsers();
printf("\nSaving the file: \n");
result = saveToFile();
printf("%i, %s, %s\n",result.code, result.message, result.payload);
printUsers();
printf("\nReading the file: \n");
result = readFromFile();
printf("%i, %s, %s\n",result.code, result.message, result.payload);
printUsers();
printf("\nDeleting all the users\n");
deleteUsers();
return(0);
}
测试读取
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "users.h"
int main() {
printf("\nReading the file: \n");
Error result = readFromFile();
printf("%i, %s, %s\n",result.code, result.message, result.payload);
printUsers();
printf("\nRemove all the users from memory\n");
deleteUsers();
return(0);
}
Makefile
usermake: users.c testUsers.c
gcc -o -g -O0 -o testUsers users.c testUsers.c -I .
gcc -o -g -O0 -o testRead users.c testRead.c -I .
我有以下代码:
#include <stdlib.h>
#include <stdio.h>
int main() {
void* a = malloc(10);
printf("%p\n", a);
}
编译并运行时:
clang-19 -std=c23 -fsanitize=address -g -Weverything -o test_mem.exe test_mem.c
./test_mem.exe
0x502000000010
=================================================================
==212167==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 10 byte(s) in 1 object(s) allocated from:
#0 0x55f0442625cf in malloc (/home/xxx/xxx/xxx/test_mem.exe+0xcb5cf) (BuildId: fe83f3b1cd62d6171e5d431d34ee529cce48f18f)
#1 0x55f0442a2a68 in main /xxx/xxx/xxx/xxx/test_mem.c:8:11
#2 0x7fa09f96fd8f in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16
SUMMARY: AddressSanitizer: 10 byte(s) leaked in 1 allocation(s).
检测到内存泄漏。太棒了!
但是,如果我将代码更改为:
#include <stdio.h>
#include <stdlib.h>
void* a = nullptr;
int main() {
a = malloc(10);
printf("%p\n", a);
}
并编译/运行:
clang-19 -std=c23 -fsanitize=address -g -Weverything -o test_mem.exe test_mem.c
... compiler complains about `int* a` not being static, fine...
./test_mem.exe
0x502000000010
未检测到内存泄漏。执行此int* a
static
操作不会改变此行为(编译器只是将其报告为警告)。
我确信有一个“充分的理由”来解释为什么全局声明变量时不会报告内存泄漏,但是:
为什么会这样?这种行为有具体的原因吗?当在全局范围内声明变量时,即使是动态分配的,其内存也会自动释放吗?如果是这样,是否意味着释放该内存(例如执行 free(a))不是绝对必要的?
有没有办法配置清理器或编译器来检测全局变量的内存泄漏?也许一些标志?
我正在尝试仅使用该文件将主机名解析为 IP 地址/etc/hosts
。
也就是说,如果无法在本地解析名称,则解析必定失败(即不发送 DNS 请求)。解析名称的标准方法是使用getaddrinfo
,但这将回退到 DNS。
gethostent_r
似乎是一个很好的候选者,因为它从本地主机文件返回记录,但不幸的是,我没有得到 IPv6 记录,只有 IPv4。
如何仅根据本地 /etc/hosts 文件将名称解析为 IPv4 或 IPv6 地址?
注意:这对于问题来说并不重要
我有一些宏,它们充当属性的更通用版本,我将它们附加到函数中。根据编译器和编译器版本,它们将扩展为属性(例如__attribute__((nonnull))
),或警告(例如_Pragma("message \"nonnull attribute unavailable\"")
)。由于属性宏可以按任何顺序排列,这可能导致它们混杂在一起(例如警告属性属性警告警告)。
结果是我可以得到如下代码:
#pragma message "one"
__attribute__((cold))
#pragma message "two"
__attribute__((noreturn))
#pragma message "three"
void test(void);
运行后clang
,此示例代码编译完美,并按预期打印三条消息。
input.c:1:9: warning: one [-W#pragma-messages]
#pragma message "one"
^
input.c:3:9: warning: two [-W#pragma-messages]
#pragma message "two"
^
input.c:5:9: warning: three [-W#pragma-messages]
#pragma message "three"
^
但是运行时gcc
,第二个出现错误#pragma
。如果我将其注释掉,第三个又会出现错误#pragma
。
input.c:1:9: note: ‘#pragma message: one’
1 | #pragma message "one"
| ^~~~~~~
input.c:3:9: error: expected identifier or ‘(’ before ‘#pragma’
3 | #pragma message "two"
| ^~~~~~~
input.c:1:9: note: ‘#pragma message: one’
1 | #pragma message "one"
| ^~~~~~~
input.c:5:9: error: expected identifier or ‘(’ before ‘#pragma’
5 | #pragma message "three"
| ^~~~~~~
经过实验,似乎在 之后gcc
不接受任何指令。#pragma
__attribute__
取消注释#pragma
会导致 GCC v11.4.0 上出现可重现的错误
__attribute__((nonnull))
// #pragma message "this is an error"
void test(void);
是否有任何修复或解决方案允许我将#pragma
和__attribute__
指令混合在一起gcc
,就像clang
允许一样?
--已更新,见下文--
我正在尝试将一个大小约为 680 字节的结构写入 STM32H757XIH6 中闪存的第 1 扇区、第 2 组。我对这种事情还很陌生,所以我正在慢慢地编写代码。我正在使用 STM32 HAL 驱动程序。该扇区的地址是 0x08100000。
代码如下:
typedef struct {
uint32_t data_header;
Parameter parameter[NUMBER_PARAMETERS];
int screen_paras[MAX_SCREENS][MAX_WIDGETS];
} Persistent_data;
void save_data() {
Persistent_data save_data;
uint32_t data_header = DATA_HEADER;
save_data.data_header = data_header;
memcpy(save_data.parameter, parameter, sizeof(save_data.parameter));
memcpy(save_data.screen_paras, screen_paras, sizeof(save_data.screen_paras));
size_t size = sizeof(Persistent_data);
uint32_t word_count = (size + 3) / 4; //32bit alignment
Flash_Write(FLASH_START_ADDRESS, (uint32_t*)&save_data, word_count);
}
HAL_StatusTypeDef Flash_Write(uint32_t address, uint32_t* data, uint32_t length) {
HAL_StatusTypeDef status = HAL_OK;
// Ensure address is within the flash range
if (address < FLASH_USER_START_ADDR || (address + length) > FLASH_USER_END_ADDR) {
return HAL_ERROR;
}
// Unlock the Flash
HAL_FLASH_Unlock();
// Erase the flash sector
FLASH_EraseInitTypeDef eraseInitStruct = {
.TypeErase = FLASH_TYPEERASE_SECTORS,
.Banks = FLASH_BANK_2,
.Sector = FLASH_SECTOR_1,
.NbSectors = 1,
.VoltageRange = FLASH_VOLTAGE_RANGE_3,
};
uint32_t sectorError = 0;
status = HAL_FLASHEx_Erase(&eraseInitStruct, §orError);
if (status != HAL_OK) {
HAL_FLASH_Lock();
return status;
}
// Write the data
for (int i = 0; i < length / 4; i++) { // Writing 32-bit words
status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, address, data[i]);
if (status != HAL_OK) {
break;
}
address += 4; // Increment address by 4 bytes (32 bits)
}
// Lock the Flash
HAL_FLASH_Lock();
return status;
}
当我尝试保存 save_data (及其所有成员)时,该行会产生硬故障status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, address, data[i]);
进一步追踪它,它进入了*dest_addr = *src_addr;
stm32h7xx_hal_flash.c。从那里我不确定如何解释崩溃堆栈,接下来是<signal handler called>() at 0xffffffed
ffffffed: Failed to execute MI command:
-data-disassemble -s 4294967277 -e 4294967529 -- 3
Error message from debugger back end:
Cannot access memory at address 0xffffffec
如果我可以提供更多信息,请告诉我
-----更新 1:---- 我已根据建议更新了代码以适应 256 位/32 字节字。新代码片段:
typedef struct {
uint32_t data_header;
Parameter parameter[NUMBER_PARAMETERS];
int screen_paras[MAX_SCREENS][MAX_WIDGETS];
} Persistent_data;
void save_data() {
Persistent_data save_data;
uint32_t data_header = DATA_HEADER;
save_data.data_header = data_header;
memcpy(save_data.parameter, parameter, sizeof(save_data.parameter));
memcpy(save_data.screen_paras, screen_paras, sizeof(save_data.screen_paras));
size_t size = sizeof(Persistent_data);
uint32_t word_count = (size + 31) / 32; //32bit alignment
Flash_Write(FLASH_START_ADDRESS, (uint32_t*)&save_data, word_count);
}
void load_data() {
Persistent_data load_data;
size_t size = sizeof(Persistent_data);
uint32_t word_count = (size + 31) / 32; //align
Flash_Read(FLASH_START_ADDRESS, (uint32_t*)&load_data, word_count);
if (load_data.data_header == DATA_HEADER) {
memcpy(parameter, load_data.parameter, sizeof(parameter));
memcpy(screen_paras, load_data.screen_paras, sizeof(screen_paras));
}
}
HAL_StatusTypeDef Flash_Write(uint32_t address, uint32_t* data, uint32_t length) {
HAL_StatusTypeDef status = HAL_OK;
// Ensure address is within the flash range
if (address < FLASH_USER_START_ADDR || (address + length) > FLASH_USER_END_ADDR) {
return HAL_ERROR;
}
// Unlock the Flash
HAL_FLASH_Unlock();
// Erase the flash sector
FLASH_EraseInitTypeDef eraseInitStruct = {
.TypeErase = FLASH_TYPEERASE_SECTORS,
.Banks = FLASH_BANK_2,
.Sector = FLASH_SECTOR_1,
.NbSectors = 1,
.VoltageRange = FLASH_VOLTAGE_RANGE_3,
};
uint32_t sectorError = 0;
status = HAL_FLASHEx_Erase(&eraseInitStruct, §orError);
if (status != HAL_OK) {
HAL_FLASH_Lock();
return status;
}
//Write the data
for (int i = 0; i < length / 32; i++) { // Writing 32-byte (256 bit) words
status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, address, (uint32_t)&data[i * 8]);
if (status != HAL_OK) {
break;
}
address += 32; // Increment address by 32 bytes (256 bits)
}
// Lock the Flash
HAL_FLASH_Lock();
return status;
}
/**
* @brief Read data from flash memory
* @param address Start address to read (must be 256-bit aligned)
* @param data Pointer to the buffer to store the read data
* @param length Number of bytes to read (must be a multiple of 32)
*/
void Flash_Read(uint32_t address, uint32_t* data, uint32_t length) {
if (address < FLASH_USER_START_ADDR || (address + length) > FLASH_USER_END_ADDR) {
return; // Out of bounds
}
for (uint32_t i = 0; i < length / 32; i++) { // Reading 32-byte (256-bit) words
// Read 32 bytes (256 bits) from flash starting at the given address
for (uint32_t j = 0; j < 8; j++) {
data[i * 8 + j] = *(__IO uint32_t*)(address + j * 4); // 4 bytes per uint32_t word
}
address += 32; // Increment address by 32 bytes (256 bits)
}
}
新问题:当我读回数据时,它不正确。data_header 不匹配。那里有数据,但都不正确。这可能与我引用/使用指针的方式有关吗?或者与内存迭代的方式有关?
我目前正在实现自己的“ls”命令。我一直依赖该结构,但我发现一篇旧帖子指出d_type
不应使用该结构的某些成员,例如。
我已经能够列出存储库中的文件,但我想根据文件类型对文件进行排序,这就是我发帖的原因。
所以我只是想知道除了使用它之外是否还有其他方法d_type
,或者使用它是否实际上没有错。
我在我的程序中发现了一个奇怪的东西。以下是两个例子
#include <stdio.h>
int main() {
time_t t1, t2;
t1 = 1735689614;
t2 = 1735689600;
printf("difftime =%d \n", difftime(t1, t2)); // difftime() return int
}
#include <stdio.h>
#include <time.h>
int main() {
time_t t1, t2;
t1 = 1735689614.0;
t2 = 1735689600.0;
printf("difftime =%f \n", difftime(t1, t2)); // difftime() return double
}
你可能会注意到#include<time.h>
,返回值difftime()
两个例子的difftime()
是不同的函数。
我知道double difftime()
是 的标准函数time.h (C11)
。但是 是从哪里来的呢int difftime()
?
这是在 vs2022 中用 c 编程时的一个非常奇怪和微妙的问题。我在 vs2022 中将 c 标准更改为C11
。程序编译成功。我以为它会使用double difftime()
不带的#inlcude<time.h>
。
虽然在使用时可以清楚地看到这个问题gcc
implicit declaration of function 'difftime' [-Wimplicit-function-declaration]
我试图解答这个练习
练习 2-7 编写函数 rightrot(b, n),将整数 b 向右旋转 n 位。
我确实编写了代码,代码如下
#include <stdio.h>
int rightrot(int b, int n) {
char i = 1;
while (n > 0) {
if ((b & i) == i) {
b = b >> 1;
b = b << 25;
b = ~b;
b = b >> 1;
b = ~b;
b = b >> 24;
}
else
b = b >> 1;
n--;
}
return b;
}
int main() {
int i, j, k;
printf("Enter number: ");
scanf("%d", &i);
printf("Enter rotation: ");
scanf("%d", &j);
k = rightrot(i, j);
printf("%d\n", k);
return 0;
}
输入和输出是
Enter number: 153
Enter rotation: 3
-13
153 的二进制表示为 000000000000000000000000010011001,因此当它进入 while 循环时,它会第一次进入 if (当 n 为 3 时),并且如您所见,里面有 6 行代码使用按位运算符来操作 b,我认为这 6 行应该如何改变 b
00000000000000000000000001001100
10011000000000000000000000000000
01100111111111111111111111111111
00110011111111111111111111111111
11001100000000000000000000000000
00000000000000000000000011001100
然后 n 是 2,然后其他 2 个 while 循环应该通过,否则我不会解释,因为如果 6 行代码本身不能按我想要的方式工作,我知道这一点是因为我分别测试了它们。
另外,这一切都是为了我将二进制旋转为 8 位而不是 32 位。
最终输出应该是 51,我使用的是完全更新的 64 位 arch linux,终端是 suckless 的 st,文本编辑器是 vim,我使用“gcc main.c -o main”编译了代码。
我正在使用除法将无符号整数转换为二进制。我有以下代码。但是,编译和执行后,我没有从程序中获得任何输出(我只是得到了换行符)。
#include <stdio.h>
/*
unsigned int is 0 or greater than 0
convert unsigned int into binary.
*/
const int ARRAY_SIZE = 100;
void reverseCharArray(char *x, int len) {
for (int end = len - 1, beg = 0; beg < end; end--, beg++) {
char temp = x[beg];
x[beg] = x[end];
x[end] = temp;
}
}
void convertWholeNumberToBinary(unsigned int x, char *result) {
int i = 0;
while (x != 0) {
result[i] = x % 2;
x = x / 2;
i++;
}
reverseCharArray(result, ARRAY_SIZE);
}
int main() {
char result[ARRAY_SIZE];
convertWholeNumberToBinary(294, result);
// 100100110
printf("%s\n", result);
return 0;
}
当输入为 294 时,期望输出为“100100110”。我期望 stdout 显示“100100110”。我知道我遗漏了一些东西,但目前我无法理解。