2011-10-22 3 views
-2

문자열을 N 개의 문자 조각으로 다듬은 다음 문자열 배열로 함수에 전달할 수 있습니까?함수에 문자열 배열을 자르고 전달할 수 있습니까?

바이너리를 < -> hex로 변환하는 내 프로그램의 일부입니다.

문자열을 사용하여 동일한 작업을 시도했지만 작동하지 않았습니다.

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

#define MAXDIGITS 8 // 8bits 


int main() 
{ 
    int y; 

    printf("Binary-Hex convertor\n"); 
    printf("Enter the Binary value : "); 
    scanf("%d", &y); 

    int i = MAXDIGITS - 1; 
    int array[MAXDIGITS]; 

    while(y > 0) 
    { 
     array[i--] = y % 10; 
     y /= 10; 
    } 

    printf("%s", "-----------------\n"); 
    printf("%s", "HEX:"); 

    int x = array[0]; 
    int x1 = array[1]; 
    int x2 = array[2]; 
    int x3 = array[3]; 
    int x4 = array[4]; 
    int x5 = array[5]; 
    int x6 = array[6]; 
    int x7 = array[7]; 

    char buffer[50]; 
    char buffer2[50]; 
    char buffer3[50]; 
} 
+0

는 ... 그것은 숙제 그래서 스마트 – BlackBear

+0

를 추측! 숙제가 아닙니다. 숙제 일지라도, 왜 다른 사람들과 지식을 공유하지 않습니까? – Faisal

+0

당신이 시도한 것을 보여줄 수 있습니까? –

답변

1

문자열에서 진수하는 그것의 단지 바이너리 다음이 훨씬 쉽게 경우 ....

char *input_string = "1001010101001010"; 
int count = 0; 
int value = 0; 

while (*input_string != '\0') 
{ 
    // Might be worth checking for only 0 and 1 in input string 
    value <<= 1; 
    value |= (int)((*input_string--) - '0'); 

    if (++count == 8 || *input_string == '\0') 
    { 
     // USE value to print etc, if you want to display use 
     // the following else you could store this in an array etc. 
     printf("%x ", value); 
     count = 0; 
     value = 0; 
    } 
} 
0

문자열을 종료해야합니까? 사용 된 메모리에 제한이 있습니까? 메모리를 올바르게 할당해야합니까? 조금 더 많은 정보가 유용 할 것입니다.

const char *input_string = "HELLO THIS IS SOME INPUT STRING"; 
int N = 4; // The number to split on 

// Work out how many strings we will end up in 
int number_of_strings = (strlen(input_string) + (N - 1))/N; 

// ALlow for an extra string if you want to null terminate the list 
int memory_needed = ((number_of_strings + 1) * sizeof(char *)) + (number_of_strings * (N + 1)); 
char *buffer = malloc(memory_needed); 
char **pointers = (char **)buffer; 
char *string_start = (buffer + ((number_of_strings + 1) * sizeof(char *)); 
int count = 0; 

while (*input_string != '\0') 
{ 
    // Fresh string 
    if (count == 0) 
    { 
     *pointers++ = string_start; 
     *pointers = NULL; // Lazy null terminate 
    } 

    // Copy a character 
    *string_start++ = *input_string++; 
    *string_start = '\0'; // Again lazy terminat  

    count++; 

    if (count == N) 
    { 
     count = 0; 
     string_start++; // Move past the null terminated string 
    } 
} 

그런 다음 (char **) 버퍼를 전달할 수 있습니다. 루틴으로. 나는 실제로 이것을 시험해 보지 않았다. 문자열을 종료하는 데는 게으르다. 카운트 실행이 끝나고 while 루프가 끝날 때만 종료 할 수 있습니다. 이것은 꽤 좋은 코드는 아니지만 일을해야합니다. 다른 요구 사항에 대한 좀 더 많은 정보가 도움이 될 수 있습니다.

관련 문제