我正在尝试在C中创建一个函数,您输入一个整数作为参数,函数将使用putchar()其二进制值输出.因此,例如,在32位系统上,-1作为参数将打印出char"1"(或int 49)32次(2的补码).
我的功能就是这样......但不知何故,应该打印出来的最后4个不是"1"(或者是第49个).但相反,我得到int 17,然后int 1三次.
这是代码:
int putbin(unsigned int b) {
int zero = 48;
int i = 0;
if (b == 0) {
putchar('0');
} else {
while (b != b % 2){
// putchar(b & 1 + 48);
printf("test %d:",i);
printf("%d ",b & 1 + zero);
printf("%d ",b);
printf("%d ",b & 1);
printf("%d ",zero);
newline();
b = b >> 1;
i++;
}
printf("last one ");
putchar(b + '0');
}
}
Run Code Online (Sandbox Code Playgroud)
我根本不应该使用它printf(),但是为了密切注意我暂时使用它的变量.
调用函数:
putbin(-1)
Run Code Online (Sandbox Code Playgroud)
输出这个: …
我正在尝试用 C 语言实现堆栈/链表。我正在为pop堆栈的功能而苦苦挣扎。
这是我的堆栈/链表实现的样子:
// a cell
struct cell_s
{
void *elem;
struct cell_s *next;
};
typedef struct cell_s cell_t;
// the list is a pointer to the first cell
struct linkedlist_s
{
struct cell_s *head;
int len;
};
typedef struct linkedlist_s linkedlist_t;
Run Code Online (Sandbox Code Playgroud)
这是弹出功能:
/**
* Pop remove and return the head
*/
cell_t *pop(linkedlist_t *list)
{
if ((*list).len == 0) {
// we cannot pop an empty list
return NULL;
}
else
{
cell_t* tmp = (*list).head; …Run Code Online (Sandbox Code Playgroud)