• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

need help with C

Status
Not open for further replies.

7imz

Member
i have this assignment, i need to read binary from a file and convert it to hex...

the format of the file is, for example

6 3
101011
001010
110101

6 and 3 are the length and the width and the rest are the binary numbers... now i have to read the file line by line... if the numbers are less than 8... i have to add 2 0's at the beginning then convert to hex... if there are 13 numbers, i have to add 3 0's at the beginning then convert to hex and so and so forth...

i'm reading the file using stdin (a1 < text.txt)

i can't use arrays btw... how can i read the required amount of numbers... if i use 8 number variables... it will start reading the next line.... :(
 

Lathentar

Looking for Pants
Using scanf, I believe you can read in binary (not sure though). If not you can do a loop and multiple by 2 then add 1 or 0 to the number depending on the input.

Take that integer and output it using printf with the hex formatting.
 

RiZ III

Member
Well if I understand right then you can do something of the following. This probably isn't the most efficient way of doing it but for a small assignment that really doesnt matter.

Have a counter representing the exponent. So if theres eight number, then the exponent starts at 8. Go through each number add em up. Something of the following.

Note: This is a mix of psuedo code and code.


int exponent = 8; //this could be six or 16 or whatever
int sum = 0;

//go through all the lines
for(int h = 0; h < height; h++)
{

//go through each character
for(int w = 0; w < width; w++)
{
char c;
file.Get(C); //get a character
sum += (int(c - 48)) << exponent--; //convert the number u just got to an int,shift it by
//exponent and then subtract the exponent
}

}


That there should get u ur sum for all the lines. U can convert to hex from there?
 
Status
Not open for further replies.
Top Bottom