Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何在我的6位二进制之前加0,使其成为7位_C - Fatal编程技术网

C 如何在我的6位二进制之前加0,使其成为7位

C 如何在我的6位二进制之前加0,使其成为7位,c,C,所以我在写一个程序,它一个字符接一个字符地输入,并将每个字符转换成二进制值。然后将二进制转换为随机字母,每个字母的ascii码值为偶数或奇数,偶数表示0,赔率表示1。我的程序完全按照预期工作,除了二进制数应该有一个0作为第一位数字。 例如。 “H”=“IVLSXDX”转换为1001000,即“H”的十进制值。 现在的问题是前面有0的字符,例如: “#”应转换为100011,但最终转换为1000110,这将丢弃该值并将“#”转换为“F”。 这是我的代码: #include <stdio.h

所以我在写一个程序,它一个字符接一个字符地输入,并将每个字符转换成二进制值。然后将二进制转换为随机字母,每个字母的ascii码值为偶数或奇数,偶数表示0,赔率表示1。我的程序完全按照预期工作,除了二进制数应该有一个0作为第一位数字。
例如。
“H”=“IVLSXDX”转换为1001000,即“H”的十进制值。
现在的问题是前面有0的字符,例如:
“#”应转换为100011,但最终转换为1000110,这将丢弃该值并将“#”转换为“F”。
这是我的代码:

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

/*Returns an even valued ascii uppercase letter. Random */
char genEven() {
    int value = (rand() % 13);
    char evens[13] = 
    {'B','D','F','H', 'J','L','N','P','R','T','V','X','Z'};
    return evens[value];
}

/** Returns an odd ascii uppercase letter. Random */
char genOdd() {
    int value = (rand() % 13);
    char odds[13] = 
    {'A', 'C', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S', 'U', 'W', 'Y'};
    return odds[value];
}

/* Given a decimal, returns 7 bit binary representation. */
int dToB(int n) {
    int remainder;
    int binary = 0; 
    int i = 1;
    while(n != 0) {
        remainder = n%2;
        n = n/2;
        binary= binary + (remainder*i);
        i = i*10;
    }
    return binary;
}

/*Reverses binary number for string conversion. */
int revBin(int n) {
    int remainder;
    int reversedNumber = 0;
    while(n != 0)
    {
        remainder = n%10;
        reversedNumber = reversedNumber*10 + remainder;
        n /= 10;
    }
    return reversedNumber;
}


/* Takes binary and converts to randomized letter combos. */
void bToS(int n) {
    int i = 7;
    int r = n % 10;
    char tmp;
    //FIX SO THAT IF A BINARY HAS A 0 in the highest order spot, print an even
    while(i > 0) {
        if(r == 0) {
        tmp = genEven();
            printf("(%c-%d)", tmp, tmp);
        } else {
        tmp = genOdd();
            printf("(%c-%d)",tmp,tmp);
        }
        n = n/10;
        r = n%10;
        i--;
    }
}

/* Discards to EOL. */
void discardToEOL() {
    char ch;
    do {
        scanf("%c", &ch);
    } while(ch != '\n');    
}

/* Encodes text.*/
int encode(void) {
    char ch;
    printf("? ");
    discardToEOL(); /*Discards any newlines from previous. */
    /*Get Input */
    do {
        scanf("%c", &ch);
    if (ch >= 0 && ch <= 128 && ch != 10) {
    printf("\nBinary rep of %c= %d\n", ch, dToB(ch));
    bToS(revBin(dToB(ch))); //Decimal to bin-> binary to string
    }
    } while(ch != '\n');    
    printf("\n");   
}

/** given a binary number, convert to decimal. */
int binToDec(int binary) 
{
    int decimal = 0, i = 1, remainder;
    /* Iterate until number becomes zero */
    while (binary != 0)
    {
        remainder = binary % 10;
        decimal = decimal + remainder * i;
        i = i * 2;
        binary = binary / 10;
    }
    printf("%c", decimal);
}

/* Decodes text.*/
int decode(void) {
    char ch;
    printf("? ");
    int i = 0;
    int bin = 0;
    discardToEOL(); /*Discards any newlines from previous. */
    /*Get Input */
    do {
        scanf("%c", &ch);
    if (ch >= 0 && ch <= 128 && ch != 10) {
        if(i <= 7) {
            if(ch % 2 == 0) {
                //Add 0 to end
                bin = bin * 10; //FIX
            } else {
                //Add 1 to end
                bin = (bin*10) +1; //FIX
            }
            i++;
        }
        if(i == 7) {
            //Send in for decimal conversion
            binToDec(bin);
            //Reset binary number
            bin = 0;
            i = 0;
        }
    }
    } while(ch != '\n');    
    printf("\n");
}

/* Main */
int main(void) {
  int c = 1;
  printf("C/c : Encode\nD/d : Decode\nQ/q : Quit\n");
  while(c) {
    printf("> "); 
    char choice;
    scanf(" %c", &choice);
    switch(choice) {
      case 'c':
        encode();
        break;
      case 'C':
        encode();
        break;
      case 'd':
        decode();
        break;
      case 'D':
        decode();
        break;
      case 'q':
        c = 0;
        break;
      case 'Q':
        c = 0;
        break;
      default:
        printf("Invalid Input.\n");  
        break;
    }
  }
}
#包括
#包括
/*返回偶数值ascii大写字母。随机的*/
char genEven(){
int值=(rand()%13);
char evens[13]=
{'B','D','F','H','J','L','N','P','R','T','V','X','Z'};
返回偶数[值];
}
/**返回奇数ascii大写字母。随机的*/
char-genOdd(){
int值=(rand()%13);
char赔率[13]=
{'A','C','E','G','I','K','M','O','Q','S','U','W','Y'};
回报率[价值];
}
/*给定一个十进制数,返回7位二进制表示形式*/
int dToB(int n){
整数余数;
int二进制=0;
int i=1;
而(n!=0){
余数=n%2;
n=n/2;
二进制=二进制+(余数*i);
i=i*10;
}
返回二进制;
}
/*为字符串转换反转二进制数*/
整数revBin(整数n){
整数余数;
int reversedNumber=0;
而(n!=0)
{
余数=n%10;
反向编号=反向编号*10+余数;
n/=10;
}
返回反向编号;
}
/*接受二进制并转换为随机字母组合*/
无效BTO(整数n){
int i=7;
int r=n%10;
char-tmp;
//修正后,如果二进制文件的最高点为0,则打印偶数
而(i>0){
如果(r==0){
tmp=genEven();
printf((%c-%d)”,tmp,tmp);
}否则{
tmp=genOdd();
printf((%c-%d)”,tmp,tmp);
}
n=n/10;
r=n%10;
我--;
}
}
/*丢弃到EOL*/
无效TOEOL(){
char ch;
做{
scanf(“%c”和“ch”);
}而(ch!='\n');
}
/*对文本进行编码*/
整数编码(空){
char ch;
printf(“?”);
DiscardorToeol();/*放弃上一页中的任何换行*/
/*获取输入*/
做{
scanf(“%c”和“ch”);
如果(ch>=0&&ch二进制到字符串
}
}而(ch!='\n');
printf(“\n”);
}
/**给定一个二进制数,将其转换为十进制数*/
int binToDec(int二进制)
{
整数十进制=0,i=1,余数;
/*迭代直到数字变为零*/
while(二进制!=0)
{
余数=二进制%10;
十进制=十进制+余数*i;
i=i*2;
二进制=二进制/10;
}
printf(“%c”,十进制);
}
/*解码文本*/
整数解码(无效){
char ch;
printf(“?”);
int i=0;
int-bin=0;
DiscardorToeol();/*放弃上一页中的任何换行*/
/*获取输入*/
做{
scanf(“%c”和“ch”);

如果(ch>=0&&ch填充转换时出现的问题是由于逻辑错误。要为转换提供填充,只需输出
8位
字符
中的所有位。要仅输出
7位
,则输出每个字符的未添加表示)。由您决定要输出的每个位和每个字符


举例来说,要仅输出任何字符的7位表示形式(
0为什么要返回
int
进行
char
到二进制的转换?(另外
uint8\u t
将是更好的类型)您的
char
将具有
8位
,而不管它包含的字母是什么(第6位为确定大写/小写的大小写位)。是否填充第7位在很大程度上是无关紧要的。您指的是哪种返回?我对C不熟悉,我来自Java。因此,当您反转一个数字时,任何帮助都将非常感激,您如何处理尾随的零?例如,1011、10110和101100都将生成1101
dToB
revBin
。您可以这样做吗从一个
char
开始,然后转换为
int
,如果存储为
little endian
将首先放置较低的8位,等等。我有点了解这里发生了什么,但我对如何将此代码实现为我自己的代码有点不知所措。我想用您提供的binpad函数替换我的dToB函数吗让它返回而不是打印?第二个输出似乎是我所需要的,因为它有前导0'sWell,您的代码对如何测试
奇数/偶数
有点误解。您测试
0位
,例如
if(val&1){…它是奇数…}否则{…它是偶数…}
。上面的每个函数只吐出所提供的任何字符(或任何数字)的
0000000
00000000
(7或8位)。您只关心字符,所以ASCII值的7位。试试看,我很乐意进一步提供帮助,但我尽量避免为您做所有工作(我很高兴在此过程中为您提供帮助)我将给您一个提示。您可以通过切换位打开/关闭来随机更改字符。要执行此操作,您只需在切换位的情况下打开/关闭任何位
n
介于
0-7
之间的位,就可以使用
XOR
(例如
newchar=char^=(1“逐位”)哈哈哈,我感谢你的帮助。为了学习,编译时一定要启用警告,例如编译字符串中的
-Wall-Wextra
,并且在没有警告的情况下编译代码之前不要接受代码。当你遇到问题时……看鸭子并与之交谈……(真的,鸭子…)如果失败,请编辑您的问题并添加您正在处理的当前代码(不要替换原始问题中的代码,请在更改之前回答)
/** unpadded binary representation of 'v'. */
void binprn (const uint64_t v)
{
    if (!v)  { putchar ('0'); return; };

    size_t sz = sizeof v * CHAR_BIT;
    uint64_t rem = 0;

    while (sz--)
        if ((rem = v >> sz))
            putchar ((rem & 1) ? '1' : '0');
}
/** binary representation of 'v' padded to 'sz' bits.
 *  the padding amount is limited to the number of
 *  bits in 'v'. valid range: 0 - sizeof v * CHAR_BIT.
 */
void binpad (const uint64_t v, size_t sz)
{
    if (!sz) { fprintf (stderr, "error: invalid sz.\n"); return; }
    if (!v)  { while (sz--) putchar ('0'); return; }

    if (sz > sizeof v * CHAR_BIT)
        sz = sizeof v * CHAR_BIT;

    while (sz--)
        putchar ((v >> sz & 1) ? '1' : '0');
}
#include <stdio.h>
#include <stdint.h>     /* for exact width types */
#include <limits.h>     /* for CHAR_BIT */

/** unpadded binary representation of 'v'. */
void binprn (const uint64_t v)
{
    if (!v)  { putchar ('0'); return; };

    size_t sz = sizeof v * CHAR_BIT;
    uint64_t rem = 0;

    while (sz--)
        if ((rem = v >> sz))
            putchar ((rem & 1) ? '1' : '0');
}

/** binary representation of 'v' padded to 'sz' bits.
 *  the padding amount is limited to the number of
 *  bits in 'v'. valid range: 0 - sizeof v * CHAR_BIT.
 */
void binpad (const uint64_t v, size_t sz)
{
    if (!sz) { fprintf (stderr, "error: invalid sz.\n"); return; }
    if (!v)  { while (sz--) putchar ('0'); return; }

    if (sz > sizeof v * CHAR_BIT)
        sz = sizeof v * CHAR_BIT;

    while (sz--)
        putchar ((v >> sz & 1) ? '1' : '0');
}

int main (void) {

    /* output binary `a` - `z` unpadded */
    for (int i = 'a'; i <= 'z'; i++) {
        printf (" %c - ", i);
        binprn (i);
        putchar ('\n');
    }

    putchar ('\n');

    /* output binary `a` - `z` padded to CHAR_BIT bits */
    for (int i = 'a'; i <= 'z'; i++) {
        printf (" %c - ", i);
        binpad (i, CHAR_BIT);
        putchar ('\n');
    }

    return 0;
}
$ ./bin/binchar
 a - 1100001
 b - 1100010
 c - 1100011
 d - 1100100
 <snip>
 x - 1111000
 y - 1111001
 z - 1111010

 a - 01100001
 b - 01100010
 c - 01100011
 d - 01100100
 <snip>
 x - 01111000
 y - 01111001
 z - 01111010
/* Discards to EOL. */
void discardToEOL ()
{
    int c;
    for (c = getchar (); c != '\n' && c != EOF; c = getchar()) {}
}
/* Decodes binary text.*/
void decode (void)
{
    int ch, i = 0, bin = 0;

    discardToEOL ();    /* discards all chars in input buffer (stdin) */

    printf ("? ");

    for (;;) {
        /* loop reading ch until valid ch received, checking for EOF */
        while ((ch = getchar()) != '\n' && ch != EOF) {
            if (ch == '0' || ch == '1')
                break;
            fprintf (stderr, "error: invalid input.\n? ");
        }
        if (ch == EOF) {    /* alway check EOF */
            fprintf (stderr, "error: user canceled input.\n");
            exit (EXIT_SUCCESS);
        }
        if (ch == '\n')     /* if ch = '\n', your done */
            break;

        ch -= '0';  /* convert ASCII character to decimal value */

        if (i <= 7) {
            /* short form of what is commented below */
            bin = (ch & 1) ? (bin << 1) | 1 : bin << 1;
            // if (!(ch & 1))
            //     bin <<= 1;              /* add 0 to end */
            // else
            //     bin = (bin << 1) | 1;   /* add 1 to end */
            i++;
        }
        if (i == 7) {
            binToDec (bin); /* send in for decimal conversion */
            bin = i = 0;    /* reset bin and i */
        }
    }

    printf ("\n");
}
/** given a binary number, convert to decimal. */
void binToDec (int binary)
{
    int decimal = 0, i = 1;

    /* Iterate until number becomes zero */
    while (binary != 0) {
        decimal += (binary & 1) * i;    /* your conversion was wrong */
        i = i * 2;
        binary >>= 1;
    }
    printf ("%c [%d]", decimal, decimal);
}
/* Encodes text.*/
void encode (void)
{
    char ch;

    discardToEOL ();        /*Discards any newlines from previous. */

    printf ("? ");

    do {
        int retval;     /* always ALWAYS check the return of scanf */

        while ((retval = scanf ("%c", &ch)) != 1) { /*Get Input */
            if (retval == EOF) {    /* alway check EOF */
                fprintf (stderr, "error: user canceled input.\n");
                exit (EXIT_SUCCESS);
            }
            fprintf (stderr, "error: invalid input.\n? ");
        }
        if (ch >= 0 && ch != '\n') {
            /* tack your zero on here :) */
            printf ("\nBinary rep of %c= 0%d\n", ch, dToB (ch));
            bToS (revBin (dToB (ch)));  //Decimal to bin-> binary to string
        }
    } while (ch != '\n');
    printf ("\n");
}
/*Returns an even valued ascii uppercase letter. Random */
char genEven ()
{
    char evens[] =
        { 'B', 'D', 'F', 'H', 'J', 'L', 'N', 'P', 'R', 'T', 'V', 'X', 'Z' };
    return evens[rand() % (sizeof evens / sizeof *evens)];
}
/* Main */
int main (void)
{
    int c = 1;

    printf ("C/c : Encode\nD/d : Decode\nQ/q : Quit\n");

    while (c) {
        char choice;
        int retval;

        printf ("> ");

        for (;;) {  /* loop until input conditions satisified */
            while ((retval = scanf (" %c", &choice)) != 1) {
                if (retval == EOF) {    /* check for manual EOF */
                    fprintf (stderr, "error: user canceled input.\n");
                    return 0;
                }
                discardToEOL ();    /* protect against multi char input */
                fprintf (stderr, "error: invalid input.\n> ");
            }
            if (((choice >> 5) & 1) == 0)   /* if lower-case bit not set */
                choice |= (1 << 5);         /* set lower-case bit */

            /* validate choice is 'c', 'd' or 'q' */
            if (choice == 'c' || choice == 'd' || choice == 'q')
                break;

            discardToEOL ();    /* protect against multi char input */
            fprintf (stderr, "error: invalid choice.\n> ");
        }

        switch (choice) {   /* handle choice */
            case 'c':
                encode ();
                break;
            case 'd':
                decode ();
                break;
            case 'q':
                c = 0;
                break;
            default:
                printf ("Invalid Input.\n");
                break;
        }
    }

    return 0;
}
$ ./bin/cbd
C/c : Encode
D/d : Decode
Q/q : Quit
> c
? abcd

Binary rep of a= 01100001
(A-65)(S-83)(X-88)(J-74)(D-68)(D-68)(Y-89)(H-72)
Binary rep of b= 01100010
(C-67)(O-79)(F-70)(H-72)(B-66)(I-73)(Z-90)(D-68)
Binary rep of c= 01100011
(S-83)(U-85)(V-86)(X-88)(P-80)(Q-81)(G-71)(H-72)
Binary rep of d= 01100100
(G-71)(K-75)(F-70)(H-72)(U-85)(J-74)(T-84)(Z-90)
> d
? 1100001
a [97]
> d
? 1100011
c [99]
> foo
error: invalid choice.
> Q