Thread: Reading char as integer.

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    30

    Reading char as integer.

    Hi.
    I want to read a matrix of 8-bit integers, in the range -127-to-128, into my program for further processing.

    My code looks like like this:

    Code:
    signed char* getdata(int rows, int columns){
    	FILE* InFile;
    	int n; 
    	int elements = 0; 
    	int siz = rows * columns;
    	int i = 0;
    	signed char* DataMatrix;
    
    	InFile = fopen("DWTinput.txt", "r");
    	DataMatrix = malloc(sizeof(char) * siz);
    	//Read matrix into array:
    	for(i = 0; i < siz; i++){
    		n = fscanf(InFile, "%c", &DataMatrix[i]); 		elements += n;
    	}
    	//Check if number of elements is correct:
    	if(elements != (siz)){
    		fprintf(stderr, "Mismatch in number of elements. Number was supposed to be %d, but is %d.", siz, elements);
    		goto error;
    	}
    	//Print matrix:
    	for(i = 0; i < siz; i++){
    		printf("%i ", DataMatrix[i]);
    	}
     
    	fclose(InFile);
    	return DataMatrix;
    
    error:
    	return NULL;
    }
    When I print the matrix, I print the ascii values.

    How can I print the integer values?

    Is it actually a good idea to use the 'char' datatype for processing integers (I should tell that I use the 'char' datatype to save memory space...), or should I use 'short int' instead?

    Thanks,

    Esben.

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    When I print the matrix, I print the ascii values.

    How can I print the integer values?
    Those are one in the same. I'm not quite sure what you expect to print. Keep in mind, all of your standard characters are within the range of 0-128. Beyond that are your extended ascii codes, which can vary from computer to computer.

    Whether or not you want to use characters to process 1 byte integers is really up to you. I wouldn't recommend it as it can be confusing to others viewing your code. Plus, in the modern age, you really don't need to be concerned too greatly with a few bytes of memory.
    Sent from my iPadŽ

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    When I print the matrix, I print the ascii values.

    How can I print the integer values?
    You mean, "How can I print 0 instead of 48?": http://faq.cprogramming.com/cgi-bin/...&id=1043284385 : Option 1.

    Hint: subtract '0'.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Is it actually a good idea to use the 'char' datatype for processing integers (I should tell that I use the 'char' datatype to save memory space...), or should I use 'short int' instead?
    Short int is generally 2 bytes, while char is always 1. A regular int is usually 4 bytes.

    Saving memmory by using smaller integer sizes is up to you. Generally, such optimisation will not save you much.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Short int is generally 2 bytes, while char is always 1. A regular int is usually 4 bytes.
    If you want to have a variable that's at least 4 bytes, use a long.

    And yes, sizeof(char) is always 1, so you can leave it out.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by dwks
    If you want to have a variable that's at least 4 bytes, use a long.
    Yes, but int is also generally 4 bytes.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  7. #7
    Registered User
    Join Date
    Mar 2006
    Posts
    30
    Hi! Thanks for your replies.
    The reason why I wanna use as small a datatype as posible preferably char, is that I need to read in a 512x512 8 bits/pxl image into a 1024KByte L2 cache.

    By using the int datatype I use 512*512*4 = 1048Kbyte. Therefore the problem.

    Esben.

  8. #8
    Registered User
    Join Date
    May 2005
    Posts
    29
    You could cast it.

    Code:
    printf("%d ", (int) DataMatrix[i]);
    Or something along those lines.

  9. #9
    Registered User
    Join Date
    Mar 2006
    Posts
    30
    Oh!
    I just think I realized something:

    If I wanna read in the number '-100' as a char, it will actually be read as 4 chars:

    32, 49, 48, 48,

    and there goes the memory savings... Right?

  10. #10
    Registered User
    Join Date
    Mar 2006
    Posts
    30
    correction to the above:

    '-100' would be read as 45, 49, 48, 48...right?

  11. #11
    Registered User
    Join Date
    Mar 2006
    Posts
    30
    Ok, more question:
    1)
    I read the array of numbers -49 -16 -67 - 80 as short integers.
    When I output them again, I write: -49 -1 - 16 -1 -67 -1 -80 -1

    Why is this?

    2)
    I tried processing the 2 above arrays in my program in the hope that the '-1's would somehow be ignored. But the the 2 outcomes of the processings were complete different. There is something basic I dont get here. Can anyone tell me what it is?

    Esben.

  12. #12
    Registered User
    Join Date
    Mar 2006
    Posts
    30
    Ok...seems I'm too quick to ask you guys advice here. At least I fount that in the following read

    fscanf(InFile, "%hi", &DataMatrix[i]);

    I should remember the 'h' in the modifier, when reading a short int.

  13. #13
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    What code are you using to read the ints?
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

  14. #14
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Its a doddle.

    printf("%d ", DataMatrix[i]);

  15. #15
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by esben
    I want to read a matrix of 8-bit integers, in the range -127-to-128, into my program for further processing.

    When I print the matrix, I print the ascii values.

    How can I print the integer values?

    Is it actually a good idea to use the 'char' datatype for processing integers (I should tell that I use the 'char' datatype to save memory space...), or should I use 'short int' instead?
    I don't think I fully follow, but here's what I think I understand:
    • You have a text file of numbers whose values are between -127 and 128*. Something like this:
      -10 -5 -4 42
      1 2 3 4
      100 -125 0 4
      -1 -1 5 9
      *If you meant -128 to 127, a char will do nicely on most common systems. If indeed you meant what you said, then you may need a bigger integer type to accomodate the 128.
    • You want to read the data into a dynamically allocated array.
    • You want to print out the value of the data contained in the char (as a small integer, not as a character).
    My rendition of this in code is something like this.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    char **ctor(int rows, int cols);
    char **read(FILE *file, char **array, int rows, int cols);
    void   show(char **array, int rows, int cols);
    void   dtor(char **array, int rows);
    
    int main()
    {
       static const char filename[] = "file.txt";
       FILE *file = fopen(filename, "r");
       if ( file != NULL )
       {
          int rows = 4, cols = 4;
          char **data = ctor(rows, cols);
          if ( data != NULL )
          {
             if ( read(file, data, rows, cols) != NULL )
             {
                show(data, rows, cols);
                dtor(data, rows);
             }
          }
          fclose(file);
       }
       else
       {
          perror(filename);
       }
    
       return 0;
    }
    
    char **ctor(int rows, int cols)
    {
       int r;
       char **array = malloc(rows * sizeof *array);
       if ( array != NULL )
       {
          for ( r = 0; r < rows; ++r )
          {
             array[r] = malloc(cols * sizeof *array[r]);
             if ( array[r] == NULL )
             {
                while ( --r >= 0)
                {
                   free(array[r]);
                }
                free(array);
                return NULL;
             }
          }
       }
       return array;
    }
    
    char **read(FILE *file, char **array, int rows, int cols)
    {
       int r, c;
       for ( r = 0; r < rows; ++r )
       {
          for ( c = 0; c < cols; ++c )
          {
             int value;
             if ( fscanf(file, "%d", &value) != 1 )
             {
                return NULL;
             }
             array[r][c] = value;
          }
       }
       return array;
    }
    
    void show(char **array, int rows, int cols)
    {
       int r, c;
       for ( r = 0; r < rows; ++r )
       {
          for ( c = 0; c < cols; ++c )
          {
             printf("%4d ", array[r][c]);
          }
          putchar('\n');
       }
       putchar('\n');
    }
    
    void dtor(char **array, int rows)
    {
       int r;
       for ( r = 0; r < rows; ++r )
       {
          free(array[r]);
       }
       free(array);
    }
    
    /* file.txt
    -10 -5 -4 42
    1 2 3 4
    100 -125 0 4
    -1 -1 5 9
    */
    
    /* my output
     -10   -5   -4   42 
       1    2    3    4 
     100 -125    0    4 
      -1   -1    5    9 
    */
    Now, can you clarify any issues that we may not be understanding?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-02-2009, 07:27 AM
  2. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  3. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  4. Searching a linked list for char
    By spentdome in forum C Programming
    Replies: 3
    Last Post: 05-22-2002, 11:11 AM
  5. Strings are V important...
    By NANO in forum C++ Programming
    Replies: 15
    Last Post: 04-14-2002, 11:57 AM