【问题标题】:How do I convert from unsigned char to long如何从 unsigned char 转换为 long
【发布时间】:2016-04-23 06:49:42
【问题描述】:

我在将 unsigned char 转换为 long 时遇到问题。

任务:我在(unsigned char) ptr->studentArr[i].subjectStatus 中有25,当i = 0 时,我进入函数unsigned char fromDecToBinary(unsigned char tmpSubjectStatus),我想在该函数中将unsigned long 11001 放入变量@ 987654326@ 然后将fprintf 放入output.txt 文件中。

期望:i = 0时fprintf进入文件11001,问题:它打印25而不是(如果我使用fromDecToBinary函数,它打印0)。

看看outPutStudentsfromDecToBinary这两个函数,其他函数正常工作,其他函数只是获取信息和存储信息。进入结构,然后用于将详细信息打印到output.txt,其中大多数都可以工作,除了二进制的东西。

input.txt 文件:

Nir 32251 99.80 11001
Ely 12347 77.89 01111
Moshe 45321 50.34 11111
Avi 31456 49.78 00011

*注意:这是不使用函数fromDecToBinary的输出 output.txt 文件:

Student 1: Nir 32251 99.80 25  
Student 2: Ely 12347 77.89 15  
Student 3: Moshe 45321 50.34 31  
Student 4: Avi 31456 49.78 3  

代码:

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

typedef struct Student{
    char* studentName; //Dyn. alloc. of stud. name
    long id; // ID Number
    float mark; // mark
    unsigned char subjectStatus;
}Student;

typedef struct University{
    Student* studentArr; // Dync. Alloc(Realloc) of students
    int numOfStudents; //num of students
}University;

void getStudents(University *ptr);
unsigned char stringToBinary(unsigned char tmpSubjectStatus[]);
void outPutStudents(University *ptr);
unsigned char fromDecToBinary(University *ptr);

void main()
{
    printf("Please enter details of student: (a)");
    University uni;
    getStudents(&uni); //Send address of structure University, because we want to change it not make a local copy of it
    outPutStudents(&uni);
    getch();
}
void getStudents(University *ptr)
{
    FILE *op;
    char tmpStudentName[20];
    long tmpId;
    float tmpMark;
    char tmpSubjectStatus[6];
    ptr->numOfStudents = 0;
    if ((op = fopen("input.txt", "r")) == NULL)
    {
        printf("Failed to open file.");
    }
    ptr->studentArr = (Student*)malloc(sizeof(Student));
    if (ptr->studentArr == NULL){
        printf("Error: memory was not allocated.");
        exit(1);
    }
    while (fscanf(op, "%s %ld %f %s", tmpStudentName, &tmpId, &tmpMark, tmpSubjectStatus) == 4)
    {
        ptr->numOfStudents++;
        ptr->studentArr = (Student*)realloc(ptr->studentArr, sizeof(Student) * ptr->numOfStudents); /*Additional code for Realloc fails - we didn't study!*/
        ptr->studentArr[ptr->numOfStudents - 1].studentName = (char*)malloc(sizeof(char)* strlen(tmpStudentName));

        if (!(ptr->studentArr[ptr->numOfStudents - 1].studentName)) //if we failed to allocate memory for studentName
        {
            while (ptr->numOfStudents > 0)
            {
                free(ptr->studentArr[ptr->numOfStudents - 1].studentName); //free  student name
                ptr->numOfStudents--; // decrease numOfStudents by one
            }
            free(ptr->studentArr); //if all student names are free, we need to free the array
            printf("Student name was not allocated.");
            exit(1);
        }

        strcpy(ptr->studentArr[ptr->numOfStudents - 1].studentName, tmpStudentName);
        ptr->studentArr[ptr->numOfStudents - 1].id = tmpId;
        ptr->studentArr[ptr->numOfStudents - 1].mark = tmpMark;
        ptr->studentArr[ptr->numOfStudents - 1].subjectStatus = stringToBinary(tmpSubjectStatus); //atoi: from "11001"(string) to 11001(int),then casting to unsigned char
    }

    fclose(op);
}
void outPutStudents(University *ptr)
{
    int i;
    FILE *fp;
    unsigned char tmpSubjectStatus;
    long val;
    if ((fp = fopen("output.txt", "w")) == NULL)
    {
        printf("Couldn't open output file.");
        exit(1);
    }
    for (i = 0; ptr->numOfStudents != i; i++){
        tmpSubjectStatus = ptr->studentArr[i].subjectStatus;
        val = fromDecToBinary(tmpSubjectStatus);
        fprintf(fp, "Student %d: %s %ld %.2f %ld  \n", i + 1, ptr->studentArr[i].studentName, ptr->studentArr[i].id, ptr->studentArr[i].mark, tmpSubjectStatus);
    }
    fclose(fp);
}

unsigned char stringToBinary(char tmpSubjectStatus[])
{
    unsigned char tmpBinaryCh = 0;
    int i;
    for (i = 0; i < 5; i++){
        if (tmpSubjectStatus[i] == '1') tmpBinaryCh += 1 << (4 - i);
    }

    return tmpBinaryCh;
}

unsigned char fromDecToBinary(unsigned char tmpSubjectStatus)
{
    int i;
    long ret;
    char arrBinary[6];
    for (i = 0; i < 5; i++){
        arrBinary[4 - i] = tmpSubjectStatus % 2;
        tmpSubjectStatus /= 2;
    }
    arrBinary[5] = '/0';

    ret = strtol(arrBinary, NULL, 10);
    return ret;
}

【问题讨论】:

  • 您不能将 11001 放入 unsigned char -- 在几乎所有计算机硬件上,unsigned char 的最大可能值为 255。
  • @BillyONeal 我明白了,那么我如何将 unsigned char 25 转换为打印 long 11001 呢?
  • 你不能。这就像在说“我如何将 5 加仑牛奶放入 1 加仑牛奶罐中”
  • @BillyONeal 好吧,我想把 unsigned char 25 存储到一个数组中作为“11001”,我使用从十进制到二进制的算法来完成,现在我想打印它包含“11001”的数组。应该是可以的。
  • @IlanAizelmanWS 打印 char 数组与 long 无关

标签: c struct


【解决方案1】:

fromDecToBinary 函数中有几个错误:

  • '/0' 替换为'\0'
  • '0' + tmpSubjectStatus % 2 存储在数组中。
  • strtol 调用添加适当的错误处理。
  • 将返回类型更改为long

【讨论】:

  • 不,retret = strtol(arrBinary, NULL, 10) 中的值仍然为零。这就是为什么我返回什么并不重要。你知道为什么会这样吗?
  • 我不知道'0' + tmpSubjectStatus % 2
【解决方案2】:

如果你想使用数字打印一些二进制,请使用这个。

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

void print_bin(uint64_t num, size_t bytes) {
  int i = 0;
  for(i = bytes * 8; i > 0; i--) {
    (i % 8 == 0) ? printf("|") : 1;
    (num & 1)    ? printf("1") : printf("0");
    num >>= 1;
  }
  printf("\n");
}

int main(void) {
  int arg = atoi("25");
  print_bin(arg, 1);
  return 0;
}

它还每 8 位打印一个垂直条,以使字节更易于阅读,但您可以将其删除。

如果你想指定你想要多少字节使用这个

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

void print_bin(uint64_t num, size_t bytes) {
  int i = 0;
  for(i = bytes * 8; i > 0; i--) {
    (i % 8 == 0) ? printf("|") : 1;
    (num & 1)    ? printf("1") : printf("0");
    num >>= 1;
  }
  printf("\n");
}

int main(void) {
  print_bin(16000, 3); 
  return 0;
}

【讨论】:

  • 二进制字符的 strlen 必须为 5,与输入中一样。我已经用我的函数 fromDecToBinary 实现了从 dec 到 binary
  • 让我更改它以使其具有动态性。两秒
  • Harry,如果您可以更改我编写的函数,我们将不胜感激,我真的不明白如何在我的代码中实现您的函数并使其工作。 :(
  • 你的函数不适合 fprintf。它只是打印到屏幕上
【解决方案3】:
#include <stdio.h>

int main()
{
unsigned char tmpSubjectStatus=25;
long quotient = tmpSubjectStatus;
long remainder;
long binary=0;
long multiplier=1;

while(quotient!=0){
     remainder=quotient % 2;
     binary=binary+(remainder*multiplier);
     multiplier=multiplier*10;
     quotient = quotient / 2;
}
     printf("%ld",binary);

return 0;
}

试试这个。 在函数中会是这样的

long fromDecToBinary(unsigned char tmpSubjectStatus)
{
long quotient = tmpSubjectStatus;
long remainder;
long binary=0;
long multiplier=1;

while(quotient!=0){
     remainder=quotient % 2;
     binary=binary+(remainder*multiplier);
     multiplier=multiplier*10;
     quotient = quotient / 2;
}

return binary;
}

这里的返回类型改为long。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    相关资源
    最近更新 更多