如何存储变量字符串数组的价值呢? [英] how to store the value of a variable to string array?

查看:129
本文介绍了如何存储变量字符串数组的价值呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我创建了一个字符串,我存储在字符串中数字的二进制值。我想存储变量 NUM 来的字符串值。

我包含给定小数number..suppose定数的二进制数的长度为A = 6,我包含3个,我需要一个字符串'结果'有'110',这是6个二进制值。

 的char *结果=(字符*)malloc的((我)* sizeof的(炭));
一世 - ;
而(A> = 1)
    {
        NUM = A%2;
        结果[I] = NUM​​; //这里我需要num的值存储在字符串中
        A = A / 2;
        一世 - ;
     }


解决方案

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&limits.h中GT;字符* numToBinStr(INT NUM){
    静态字符斌[的sizeof(int)的* CHAR_BIT + 1];
    的char * p =&放大器;仓[的sizeof(int)的* CHAR_BIT]; // p指向结束
    无符号的A =(无符号)NUM;    做{
        * - P ='0'+(A和1);
        A>> = 1;
    }而(A&0); //做,而A的情况下,值为0
    回磷;
}诠释主要(无效){
    的printf(%S \\ n,numToBinStr(6));
    //复制,如果需要的话
    //字符*斌=的strdup(numToBinStr(6));
    字符*结果= numToBinStr(6);
    字符*斌=的malloc(strlen的(结果)+ 1);
    的strcpy(斌,结果);
    的printf(%S \\ n,斌);
    免费(箱);
    返回0;
}

Here I have created a string and I am storing the binary value of a number in the string.. I want to store the value of the variable num to the string.

i contains the length of the binary number for the given decimal number..suppose the given number is A=6, i contains 3 and i need a string 'result' having '110' which is the binary value of 6.

char* result = (char *)malloc((i)* sizeof(char));
i--;
while(A>=1)
    {
        num=A%2; 
        result[i]=num;  // here I need to store the value of num in the string
        A=A/2;
        i--;
     }

解决方案

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

char *numToBinStr(int num){
    static char bin[sizeof(int) * CHAR_BIT + 1];
    char *p = &bin[sizeof(int) * CHAR_BIT];//p point to end
    unsigned A = (unsigned)num;

    do {
        *--p = '0' + (A & 1);
        A >>= 1;
    }while(A > 0);//do-while for case value of A is 0 
    return p;
}

int main(void){
    printf("%s\n", numToBinStr(6));
    //To duplicate, if necessary
    //char *bin = strdup(numToBinStr(6));
    char *result = numToBinStr(6);
    char *bin = malloc(strlen(result) + 1);
    strcpy(bin, result);
    printf("%s\n", bin);
    free(bin);
    return 0;
}

这篇关于如何存储变量字符串数组的价值呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆