小编use*_*604的帖子

如何将64位整数转换为char数组并返回?

我无法将int64_t转换为char数组并返回.我不知道下面的代码有什么问题,它对我来说完全合乎逻辑.代码适用于a如图所示,但不是第二个b明确属于int64_t范围的数字.

#include <stdio.h>
#include <stdint.h>

void int64ToChar(char mesg[], int64_t num) {
  for(int i = 0; i < 8; i++) mesg[i] = num >> (8-1-i)*8;
}

int64_t charTo64bitNum(char a[]) {
  int64_t n = 0;
  n = ((a[0] << 56) & 0xFF00000000000000U)
    | ((a[1] << 48) & 0x00FF000000000000U)
    | ((a[2] << 40) & 0x0000FF0000000000U)
    | ((a[3] << 32) & 0x000000FF00000000U)
    | ((a[4] << 24) & 0x00000000FF000000U)
    | ((a[5] << 16) & 0x0000000000FF0000U)
    | ((a[6] <<  8) & 0x000000000000FF00U) …
Run Code Online (Sandbox Code Playgroud)

c linux

11
推荐指数
1
解决办法
2万
查看次数

如何在socket编程中使用select和FD_SET?

我是新来的Socket编程,和我有麻烦了解如何select()FD_SET()作品.

我修改了Beej教程中的一个例子,试图找出它.我想在for循环中做的是每次迭代我等待4秒.如果有可用的读取,我会打印"按下一个键",如果超时,则会打印"超时".然后我会清除该设置并重复该过程9次.但似乎一旦设置了文件描述符0,即使在调用FD_ZERO()和/或之后它也永远不会被设置FD_CLR().换句话说,在循环的第一次迭代中按下一个键之后,将为剩余的迭代设置文件描述符,并且不再进行等待.所以必须有一些我缺少的东西,但我不知道是什么.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#define SERVERPORT 4950

int main(int argc, char *argv[]) {
    struct sockaddr_in their_addr; // connector's address information
    struct hostent *he;
    int numbytes;
    int broadcast = 1;

    if ((he=gethostbyname(argv[1])) == NULL) {  // get the host info
        perror("gethostbyname");
        exit(1);
    }

    // this call is what allows broadcast packets to be sent:
    if …
Run Code Online (Sandbox Code Playgroud)

sockets linux select

10
推荐指数
2
解决办法
3万
查看次数

民意调查功能如何在c中起作用?

我是socket编程的新手,我正在试图弄清楚poll是如何工作的.所以我做了一个小例子程序.该方案似乎我怎么想到的工作,但是当我注释掉具有行int dummyfor循环,只有当它的假设做10次运行一个迭代.我不明白的是该变量与for循环有什么关系.该程序假设在3.5秒后打印"超时"并且如果有可用输入则打印"返回命中".

#include <stdio.h>
#include <poll.h>

int main(int argc, char *argv[]) {
    int a;
    int b;
    int c;
    char buf[10];
    int i;
    struct pollfd ufds[1];      
    ufds[0].fd = 0;
    ufds[0].events = POLLIN;
    int rv;
    int dummy;
    for(i=0; i < 10; i++) {
        printf("%i ", i);
        if((rv = poll(ufds, 2, 3500)) == -1) perror("select");
        else if (rv == 0) printf("Timeout occurred!\n");
        else if (ufds[0].revents & POLLIN) {
            printf("return hit\n");
            read(0, buf, 10);
        }   
        fflush(stdout); 
    }   
    return …
Run Code Online (Sandbox Code Playgroud)

c sockets linux

5
推荐指数
1
解决办法
1万
查看次数

在这种情况下,最好的排序算法是什么?

myarray = empty
n = 10000
range = 1000
loop 1 to n {
    x = random number between 1 and range 
    if x not in myarray {
        add x to myarray
        sort myarray
        do something 
    }
}
Run Code Online (Sandbox Code Playgroud)

我考虑过插入排序,但这需要元素转移.并且快速排序在已经排序的列表上会很糟糕.我能想到的最好的是Min Heap.是否有一些鲜为人知的排序算法对这种情况更好?它是在C++的STL中吗?

c++ sorting

3
推荐指数
1
解决办法
347
查看次数

标签 统计

linux ×3

c ×2

sockets ×2

c++ ×1

select ×1

sorting ×1