从 char* 转换为 int

标签 c

我的代码失败并返回一个非常大的数字:

#include <stdio.h>

int main()
{
    char *s = "hello123";
    printf("%d\n",*(int *)s);
    return 0;
}

对于 atoi 它返回 0,有什么想法吗?

我想要实现的是: 例如,我向服务器软件发送“hello123”,服务器软件应该在字符串中获取“123”数字,方法如下:

uint16_t get_uint16(NetworkMessage *message)
{
    uint16_t ret = 0;
    if (!message || !message->buffer)
        return 0;

    ret = *(uint16_t *)(message->buffer + message->position);
    message->position += sizeof(uint16_t);
    return ret;
}

最佳答案

这假设您的字符串有两部分,第一个索引包含字符(例如hello),最后一个索引包含数字(例如123)。据我从您的评论中了解到,这就是您想要做的。

#include <stdio.h>  
#include <stdlib.h>

int main() 
{
     char* s = "hello123";
     char* num_ptr = s;

     while(*num_ptr < '0' || *num_ptr > '9')
          ++num_ptr;

     int number = atoi(num_ptr);

     printf("%d\n", number);
     return 0; 
}

编辑后:试试看?我假设 message_buffer 包含您的消息并且类型为 char*

int get_number(char* message_buffer)
{
     char* num_ptr = message_buffer + strlen(message_buffer) - 1;

     while(isdigit(num_ptr) && num_ptr > message_buffer)
          --num_ptr;

     int number = atoi(num_ptr);

     if(number > UINT16_RANGE)
          //Handle error here

     return number;     
}


uint16_t get_uint16(NetworkMessage *message) 
{
     uint16_t ret = 0;
     if (!message || !message->buffer)
         return 0;      

     ret = get_number(message->buffer);
     //message->position += sizeof(uint16_t);     
     return ret; 
} 

关于从 char* 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5556509/

相关文章:

c - 参数中的指针出现问题..c 中的冒泡排序

c - inet_pton() 给出 "Segmentation fault"

c - 如何确定硬盘是否处于休眠或旋转状态?

c++ - 如何从excel文件中提取数据到c?

c - wedit lcc-win32 中程序 "is not up to date"执行错误

c - 在函数之间传递 char 指针 - 两种方式是否相等? - C

c - strdup() - 它在 C 中的作用是什么?

c - 在哪里以及如何放置 typedef 结构?

c - 为什么在 Visual Studio 6.0 中找不到 errno?

c - malloc 如何申请堆内存