简体   繁体   English

如何使用C中的指针将十六进制转换为二进制

[英]How to convert from hexadecimal to binary using pointers in C

I need to make a program that resolve operations between hexadecimal, where i ask for the number of hexadecimals to operate, ask for them, and then show the result. 我需要编写一个程序来解析十六进制之间的运算,在该程序中,我询问要操作的十六进制数,询问它们,然后显示结果。

The operations that can be done are or,and,xor(|,^,&). 可以完成的运算是or,and,xor(|,^,&)。 I made the convert part with arrays where i storage the hex number, and then convert those in binary and save it in another array but when i realize i coudnt know how many integers of hex were going to operate i coudnt figure out how to create enough arrays to storage those someone told me about i had to use pointers. 我用存储十六进制数的数组制作了转换部分,然后将其转换成二进制数并将其保存在另一个数组中,但是当我意识到自己知道要操作多少个十六进制整数时,我就想出了如何创建足够的整数数组来存储那些有人告诉我的信息,我必须使用指针。 Im new to that and research a bit about that still dont know how pointers can work that out... 我对此并不陌生,并对此进行了一些研究仍然不知道指针如何解决这个问题。

Part of my code so far: 到目前为止,我的代码的一部分:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <proyecto.h>
#include <string.h>
int main () {
  char op,bin1[31]="",bin2[31]="",hex1[100],hex2[100];
  int sizeh,repeat1,repeat2,n,z,i;
              printf("Write Hexadecimal:);
              scanf("%s",hex1);
              convert(hex1,bin1,n);

function convert: 函数转换:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <proyecto.h>
#include <string.h>
void convert(char hex1[],char bin1[],int n){
int i,b;
printf("\nEquivalent binary value: ");
for(i=0;i<4;i++){
switch(hex1[i]){
case '0': strcat(bin,"0000"); break;
case '1': strcat(bin,"0001"); break;
case '2': strcat(bin,"0010"); break;
case '3': strcat(bin,"0011"); break;
case '4': strcat(bin,"0100"); break;
case '5': strcat(bin,"0101"); break;
case '6': strcat(bin,"0110"); break;
case '7': strcat(bin,"0111"); break;
case '8': strcat(bin,"1000"); break;
case '9': strcat(bin,"1001"); break;
case 'A': strcat(bin,"1010"); break;
case 'B': strcat(bin,"1011"); break;
case 'C': strcat(bin,"1100"); break;
case 'D': strcat(bin,"1101"); break;
case 'E': strcat(bin,"1110"); break;
case 'F': strcat(bin,"1111"); break;
case 'a': strcat(bin,"1010"); break;
case 'b': strcat(bin,"1011"); break;
case 'c': strcat(bin,"1100"); break;
case 'd': strcat(bin,"1101"); break;
case 'e': strcat(bin,"1110"); break;
case 'f': strcat(bin,"1111"); break;
default:  printf("\nInvalid hexadecimal digit %c ",hex[i]);
}
}
printf("%s",bin);
}

I'm still not sure, if you want to do it all with strings (you need to do so if you want to go very large without using big integers) 我仍然不确定,是否要使用字符串完成所有操作(如果要在不使用大整数的情况下变得很大就需要这样做)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// for tolower()
#include <ctype.h>

int convert(char *hex, size_t len, char **bin)
{
  size_t i;
  char c;

  for (i = 0; i < len; i++) {
    // work on lower-case to safe us some work
    c = tolower(hex[i]);
    // TODO: use a table instead of a large switch,
    //       or a union
    switch (c) {
    case '0':
      strcat(*bin, "0000");
      break;
    case '1':
      strcat(*bin, "0001");
      break;
    case '2':
      strcat(*bin, "0010");
      break;
    case '3':
      strcat(*bin, "0011");
      break;
    case '4':
      strcat(*bin, "0100");
      break;
    case '5':
      strcat(*bin, "0101");
      break;
    case '6':
      strcat(*bin, "0110");
      break;
    case '7':
      strcat(*bin, "0111");
      break;
    case '8':
      strcat(*bin, "1000");
      break;
    case '9':
      strcat(*bin, "1001");
      break;
    case 'a':
      strcat(*bin, "1010");
      break;
    case 'b':
      strcat(*bin, "1011");
      break;
    case 'c':
      strcat(*bin, "1100");
      break;
    case 'd':
      strcat(*bin, "1101");
      break;
    case 'e':
      strcat(*bin, "1110");
      break;
    case 'f':
      strcat(*bin, "1111");
      break;
    default:
        // should not happen, an error
        return -1;
        break;
    }
  }
  return len;
}

int main()
{
  // number of inputs
  int count;
  // length of input
  int len;
  // iterator
  int i;
  // first hexadecimal string (100 characters plus '\0')
  // fixed size memory because the modifier 'm' is in Posix not standard-C
  // and scanning input manually is more complicated.
  char hex[101];
  // binary strings
  // gets allocated dynamically
  char **bin;

  puts("Number of Hexadecimal:");
  scanf(" %d", &count);
  // allocate an array for the strings
  bin = malloc(count* sizeof(char *));
  // gather input
  for(i = 0;i < count;i++){
    printf("Hexadecimal #%d:",i+1);
    scanf(" %100s", hex);
    len = strlen(hex);
    //TODO: check input for correctness
    // Hint: try isxdigit() (also in ctype.h)

    // allocate memory for the individual string in the array (8 bits in a byte)
    bin[i] = malloc(len * 8 + 1);
    bin[i][0] = '\0';
    convert(hex, len, &bin[i]);
    printf("Binary #%d: %s\n",i+1,bin[i]);
  }

  // if you want to store the individual hextrings, too, just make an
  // array "hexarray" and handle it just like the "bin" array.

  // Now all hexstrings are converted and in the array "bin"
  // Do whatever you want to do with them here

  // free memory (although not needed at the end of main, just good style)
  for(i = 0;i < count;i++){
    free(bin[i]);
  }
  free(bin);

  /*
     Testvalues:
     1234abdf -> 00010010001101001010101111011111
     abdf1234 -> 10101011110111110001001000110100
   */

  // exit and return the correct value the operating system assigned to
  // "program ended without error"
  exit(EXIT_SUCCESS);
}

Edit : 编辑

C does not assume anything, you need to tell it explicitly. C不承担任何责任,您需要明确地告诉它。 So, if you want an array of something you need to tell the compiler the number of members in advance or allocate a couple of members and grow it later with realloc() , if necessary. 因此,如果需要数组数组,则需要提前告知编译器成员数,或分配几个成员,然后在必要时使用realloc()使其增长。

We know the size of the array in advance because we asked for it, hence we allocate that exact amount. 我们事先知道数组的大小是因为我们需要它,因此我们分配了确切的数量。 But that is only the array, the content needs its own memory. 但这仅仅是数组,内容需要它自己的内存。

Let me try a metaphor (a simile? I*ll never know): imagine the array as a rail with a number of hooks; 让我尝试一个比喻(一个比喻吗?我永远不会知道):将数组想象成带有多个钩子的轨道; you might find such a thing in you kitchen. 你可能会在厨房里发现这样的东西。 If you want to hang your spices at these hooks you cannot do it directly, you need to put the in a container that is large enough to keep the amount of spices you want to fill in. If the container is too small, it will flow over [sic!], if it is too big it is a waste. 如果要将香料挂在这些钩子上,则不能直接做,需要将其放入足够大的容器中,以保持要填充的香料量。如果容器太小,则会流淌如果太大,那就太浪费了。

So you need to know the minimum number of hooks (for the first malloc ) and the minimum size of the container (for the second malloc ). 因此,您需要知道最小数目的钩子(对于第一个malloc )和容器的最小大小(对于第二个malloc )。 To stretch that metaphor to its limits: I used hex as a spoon to fill the containers bin[i] . 将此隐喻扩展到其极限:我用hex作为汤匙填充了容器bin[i]

If you want to have arbitrary large input: try fgets() and company. 如果您想要任意大的输入:尝试使用fgets()和company。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM