0
#include<iostream>
#include<fstream>
#define TRANSFORMS 4
#define BLOCK 4
using namespace std;
char* img=new char[128*128*TRANSFORMS];
int main(){
ifstream File;
File.open("ficdata");
int isize=128*TRANSFORMS*128;
int inc=TRANSFORMS*128;
int jsize=128*TRANSFORMS;
int i=0,j=0,temp;
while(!File.eof())
{
    File>>temp;
    img[i+j]=temp;
    j+=TRANSFORMS;
    if(j==jsize){
        j=0;
        i+=inc;
    }
    if(i==isize){
        break;
    }
}
for(int i=0;i<isize;i+=inc){
    for(int j=0;j<jsize;j+=TRANSFORMS){
        cout<<(int)img[i+j]<<" ";
    }
}
}

In the above code snippet the file contains 128*128 values which are between 0-255.When I try to typecast the values back to int and print them I get some values as positive and some values as negative.Why does that happen?The int values are getting stored properly and the problem occurs only when typecasting them back.

  • Why are you using `new` to allocate a static, global array? – melpomene Mar 24 '18 at 11:28
  • [`while(!File.eof())` is wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – melpomene Mar 24 '18 at 11:29
  • Please read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Some programmer dude Mar 24 '18 at 11:29
  • The `File>>temp;` will skip whitespace, which is probably not what you want for a binary file, since the stream does not distinguish between a whitespace character and a binary byte of the same value. – Eljay Mar 24 '18 at 12:33

1 Answers1

1

char has implementation-defined signedness. On some platforms it has the same range as unsigned char (usually 0 .. 255), on other platforms it has the same range as signed char (usually -128 .. 127).

Apparently on your system it is signed, so storing values above 127 results in negative numbers. You can fix this by changing img to unsigned char.

Also, there's no reason I can see for img to be allocated dynamically. You could just do

unsigned char img[128*128*TRANSFORMS];
melpomene
  • 79,257
  • 6
  • 70
  • 127