To generate hexadecimal numbers for 1000 bytes in C - c

I want to generate hexadecimal numbers in C starting with seed value(initial value) 0706050403020100.My next numbers should be 0f0e0d0c0b0a0908 and so on for next iteration.
In that way i want to generate numbers for say 1000 bytes.
1)how can i generate these hexadecimal numbers.
2)How to store these numbers if i want to compare the generated/produced hexadecimal numbers character by character with the data available in a buffer(dynamic) which has contents of a read file.
Any suggestions/answers are most welcome as i am still learning C language.
EDIT:Here's the code i have tried.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *fp;
char *buffer, c;
size_t filesize, result;
int i, expected_data[];
fp = fopen("hex_data", "r");
if (fp == NULL) {
fputs("Error\n", stderr);
exit(1);
}
fseek(fp, 0L, SEEK_END);
filesize = ftell(fp);
printf("Size of hex_data file is:%u \n", filesize);
fseek(fp,0L,SEEK_SET);
buffer = (char*) malloc(sizeof(char)*filesize);
if(buffer == NULL){
fputs("\nMemory error ", stderr);
}
buffer_size = fread(buffer, sizeof(char), size, fp);
for(i=0; i < result; i++) {
printf("%c",*(buffer +i));
}
printf("No of elements read from file are:%u \n", buffer_size);
fseek(fp,0L,SEEK_SET);
int current_pos = 0;
while(current_pos < buffer_size) {
if (buffer[current_pos] != expected_data) {
fputs("Error\n",stderr);
}
else {
current_pos++;
expected_data = next_exp_data(data); //function is call hexadecimal numbers produced
}
}
Here i want to write a function to generate hex numbers for 1000 bytes starting from 0706050403020100.If this is the initial data everytime if i add 08 to each byte i should get the next number(til 1000 bytes).But i don't know how to do it.Can anyone help me out.
Any corrections in the code are most welcome.

This will generate 1000 bytes of random hexadecimal numbers. (Or rather, the ASCII representation of 1000 hexadecimal digits.)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i;
for (i=0; i<1000; i++) {
printf("%x", rand()%16);
}
printf("\n");
return EXIT_SUCCESS;
}
If you wanted to store them in a buffer to compare with something else later, you might want to look at sprintf instead of printf. For that, you really need to understand how strings are allocated and used in C first.
EDIT: This might be more what you're after. It reads hexadecimal digits from standard input (which can be redirected from a file if desired) and checks to see if they follow the pattern that you described.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int expected_number = 7;
unsigned int read_number;
while (1 == scanf("%2x", &read_number)) {
if (expected_number != read_number) {
fprintf(stderr, "Expected %02x but got %02x.\n", expected_number, read_number);
}
expected_number--;
if (expected_number == -1) expected_number = 15;
}
return EXIT_SUCCESS;
}

Your numbers are large, so use a 64-bit unsigned integer data type, such as unsigned long long. You won't be able to deal with numbers greater than 2**64 without adopting a new scheme. Print hex values using printf("%x", value).
You can look at GNU GMP library for arbitrarily large integers.

Related

Trying to add a text file into an array in C

I am trying to take 500 numbers in this text file and store them into an array, it keeps giving me random numbers that aren't in my text file at all. I've also changed a few things and it is saying that there is conflicting types for my fp_read
#include<stdio.h>
int ch;
int X[500];
FILE*fp_read = NULL;
fp_read = fopen("random_numbers.txt","r");
int main()
{
for(i=0;i<499;i++)
{
if(ch==EOF)
{
printf("End of File\n");
}
else
{
ch = (fgetc(fp));
X[i]=ch;
printf("%d,"X[i]);
}
}
return 0;
}
sorry for the quick answer but try to use atoi or strtol to convert the character to integer or add -48 because '0' in ascii is 48
You are interpreting the character codes of the digits used to encode the textual numbers, which is probably not at all what you want. For instance in UTF-8 the number "12" consists of the two code points 1 and 2, which encode as the two 8-bit values 49 and 50.
For line-based input, it's almost always best to read whole lines into a suitably large buffer, then parse that. That is more robust than parsing the stream itself.
Something like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * const fp = fopen("random-numbers.txt", "rt");
if(fp == NULL)
{
fprintf(stderr, "**File open failed\n");
exit(1);
}
int numbers[500];
int index = 0;
char line[1024];
while(fgets(line, sizeof line, fp) != NULL)
{
if(index >= sizeof numbers / sizeof *numbers)
break;
numbers[index++] = (int) strtol(line, NULL, 10);
}
printf("Read these numbers:\n");
for (int i = 0; i < index; ++i)
printf("%d: %d\n", i, numbers[i]);
return 0;
}

Reading integers from txt file in C

I`m making a file reader that reads integers numbers line by line from a file. The problem is that is not working. I think I am using fscanf in a wrong way. Can someone help me?
I had already look for answers in others questions but I can`t find anything that explain why I my code is not working.
int read_from_txt(){
FILE *file;
file = fopen("random_numbers.txt", "r");
//Counting line numbers to allocate exact memory
int i;
unsigned int lines = 0;
unsigned int *num;
char ch;
while(!feof(file)){
ch = fgetc(file);
if (ch == '\n'){
lines++;
}
}
//array size will be lines+1
num = malloc(sizeof(int)*(lines+1));
//storing random_numbers in num vector
for(i=0;i<=lines;i++){
fscanf(file, "%d", &num[i]);
printf("%d", num[i]);
}
fclose(file);
}
The txt file is like:
12
15
32
68
46
...
But the output of this code keeps giving "0000000000000000000..."
You forgot to "rewind" the file:
fseek(file, 0, SEEK_SET);
Your process of reading goes through the file twice - once to count lines, and once more to read the data. You need to go back to the beginning of the file before the second pass.
Note that you can do this in a single pass by using realloc as you go: read numbers in a loop into a temporary int, and for each successful read expand the num array by one by calling realloc. This will expand the buffer as needed, and you would not need to rewind.
Be careful to check the results of realloc before re-assigning to num to avoid memory leaks.
You could try to use the getline function from standard IO and add the parsed numbers into the array using only one loop. See the code below. Please check https://linux.die.net/man/3/getline
Also, you can use the atoi or strtoul functions to convert the read line to an integer. Feel free to check https://linux.die.net/man/3/atoi or https://linux.die.net/man/3/strtoul
The code below evaluate a file with a list of numbers and add those numbers to a C integer pointer
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char ** argv) {
FILE * file;
file = fopen("./file.txt", "r");
size_t read;
char * line = NULL;
size_t line_len = 0;
size_t buffer_size = 10;
int * buffer = (int *)malloc(sizeof(int) * buffer_size);
int seek = 0;
while((read = getline(&line, &line_len, file)) != -1) {
buffer[seek++] = atoi(line);
if (seek % 10 == 0) {
buffer_size += 10;
buffer = (int *)realloc(buffer, sizeof(int) * buffer_size);
}
}
for (int i = 0; i < seek; i++) {
printf("%d\n", buffer[i]);
}
free(buffer);
fclose(file);
}
If you aren't sure which conversion function should you use. You can check the difference between atoi and sscanf at What is the difference between sscanf or atoi to convert a string to an integer?

How to store SHA1 output to a file using C

I have computed the SHA1 for a piece of data and I need to store it into a file to be read by another person later. The SHA1 gives the output as 190 bit's, but I can't store as bits into a file, fputc() function does it characters which means bytes.
So I want to either store it as bytes into the file or as its hexadecimal representation (preferably). In C, so far I can only get it to print the hash to the terminal as the hexadecimal representation (using a way I found in another question posted in this site), but I can't figure out how to store it to a file properly.
Please help!
If you want to write the SHA1 digest as binary digest in the file, you can use:
fwrite ( &sha1_digest, sizeof(sha1_digest), 1, stream );
Where stream is a FILE* opened in binary mode.
If you want to save it as hexadecimal string, you can do a loop :
char *p=(void*)&sha1_digest;
int i=sizeof(sha1_digest);
while (i--)
fprintf (stream, "%02x",*p++);
where tream is a FILE* opened in text or binary mode
I assumed that sha1_digest was a structure. If it's an array, you don't need the & and if the array is not fixed size, then you must provide the size of the digest (because in this case, sizeof() would return the sizeof a pointer isntead of the array.)
You are certainly aware, but SHA1 is no longer considered as a safe hash, if your use is somewhat related to security.
i used the following code for generating sha1 hash of text stored in message.txt file(text is: hello how are you).
#include <stdio.h>
#include <stdlib.h>
#include <openssl/sha.h>
#define BUFSIZE 1024*16
void do_fp(FILE *f);
void pt(unsigned char *md);
#ifndef _OSD_POSIX
int read(int, void *, unsigned int);
#endif
int main(int argc, char **argv)
{
int i, err = 0;
FILE *IN,*fp;
if (argc == 1) {
do_fp(stdin);
}
else {
printf("hi");
for (i = 1; i < argc; i++) {
IN = fopen(argv[i], "r");
if (IN == NULL) {
perror(argv[i]);
err++;
continue;
}
printf("SHA1(%s)= ", argv[i]);
do_fp(IN);
fclose(IN);
}
}
exit(err);
}
void do_fp(FILE *f)
{
SHA_CTX c;
unsigned char md[SHA_DIGEST_LENGTH];
int fd;
int i;
unsigned char buf[BUFSIZE];
FILE *fp;
fd = fileno(f);
SHA1_Init(&c);
for (;;) {
i = read(fd, buf, BUFSIZE);
if (i <= 0)
break;
SHA1_Update(&c, buf, (unsigned long)i);
}
SHA1_Final(&(md[0]), &c);
fp = fopen("file.txt","wb");
char *p=(void*)md;
i=SHA_DIGEST_LENGTH;
while (i--)
fprintf (fp, "%02x",*p++);
pt(md);
}
void pt(unsigned char *md)
{
int i;
for (i = 0; i < SHA_DIGEST_LENGTH; i++)
printf("%02x", md[i]);
printf("\n");
}
i got followng as output. SHA1(message.txt)= 46e7b8310aa4d03b57e11022166d37beedf36537 however hash stored in file.txt is as follows. 46ffffffe7ffffffb8310affffffa4ffffffd03b57ffffffe11022166d37ffffffbeffffffedfffffff36537 please provide necessary guidance to achieve correct hash in file.txt. thank you in advance.

Binary Translation

#include <stdio.h>
int main() {
unsigned char data[1];
FILE *f = fopen("bill.jpg", "rb");
while (!feof(f)) {
if (fread(data, 1, 1, f) > 0) {
printf("0x%02x\n", data[0]);
}
}
fclose(f);
}
Is this the right? I am worried because if I view the file using hexdump, I get completely different output.
That should correctly print the first byte of the file in hex.
Check the documentation for the Hexdump utility used, or tell us which platform is being used. Some dump utilities display the bytes in reverse order on each line to make little-endian reading somewhat more intuitive—once you understand what it is doing.
I'm sorry, but no -- while (!feof(f)) is essentially always wrong -- it'll typically appear to read the last item in the file twice. Here's a reasonably usable hex dumper I wrote a few years ago:
/* public domain by Jerry Coffin, tested with MS C 10.0 and BC 4.5
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
unsigned long offset = 0;
FILE *input;
int bytes, i, j;
unsigned char buffer[16];
char outbuffer[60];
if ( argc < 2 ) {
fprintf(stderr, "\nUsage: dump filename [filename...]");
return EXIT_FAILURE;
}
for (j=1;j<argc; ++j) {
if ( NULL ==(input=fopen(argv[j], "rb")))
continue;
printf("\n%s:\n", argv[j]);
while (0 < (bytes=fread(buffer, 1, 16, input))) {
sprintf(outbuffer, "%8.8lx: ", offset+=16);
for (i=0;i<bytes;i++) {
sprintf(outbuffer+10+3*i, "%2.2X ",buffer[i]);
if (!isprint(buffer[i]))
buffer[i] = '.';
}
printf("%-60s %*.*s\n", outbuffer, bytes, bytes, buffer);
}
fclose(input);
}
return 0;
}

C programming involving files and structures

how to read a negative number from a file using fgetc?
fgetc only reads one character at a time. If you are trying to read in a negative number from a file -- or any number -- use fscanf.
#include <stdio.h>
main()
{
int v;
fscanf (stdin, "%d", &v);
printf ("v = %d\n", v);
}
If the "structures" in the title implies binary, then you likely want to use fread(), but if you really are chasing the question of what the layout of the integer stored in a binary file is, you can use fgetc().
This code shows how to use a union to map a series of read bytes back into an integer.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
union Integer
{
int intPart_;
char charPart_[4];
};
int main(int argc, char* argv[])
{
FILE* pFile = fopen("integerFile.dat", "w");
int intWritten = -257;
size_t bytesWritten = fwrite(&intWritten, 1, sizeof(int), pFile);
assert(bytesWritten == sizeof(int));
fclose(pFile);
pFile = fopen("integerFile.dat", "r");
int intRead = 0;
size_t bytesRead = fread(&intRead, 1, sizeof(int), pFile);
assert(bytesRead == sizeof(int));
printf("%d\n", intRead);
fclose(pFile);
pFile = fopen("integerFile.dat", "r");
Integer intToRead;
for(int i = 0;
i != sizeof(int);
++i)
{
int byteRead = fgetc(pFile);
intToRead.charPart_[i] = byteRead;
printf("%d\n", byteRead );
}
printf("%d\n", intToRead.intPart_);
fclose(pFile);
return 0;
}
How's the number encoded?
If it's ASCII, remember it takes more than one character. You can write a loop for it, but you might find fscanf more help.
If it's binary data, remember fgetc is only going to read 8 bits anyway -- again, you need to think about other functions to do it efficiently.
The point here really is that unless you're doing it just to prove you can, fgetc is probably the wrong answer. Maybe fgets?
fgetc() interprets the character as an "unsigned char", but casts it to an int (but returns EOF, which is -1, on end of file).
If your source file contains some representation of signed values, then you need to decode that.
'0' has the ascii value 0x30、'1' is 0x31... and so far...
Assuming you have only one number in your file:
FILE * pFile;
int c, n = 0;
bool negative;
pFile=fopen ("myfile.txt","r");
if (pFile==NULL){
perror("Error opening file");
}else{
c = fgetc (pFile);
negative = (c == '-');
do {
c = fgetc (pFile);
if (c>=0x30 && c<=0x39) {
n = n*10 + (c-0x30);
}
} while (c != EOF);
fclose (pFile);
}
if(negative==true) n=n*-1;
printf ("Your number: %d\n",n);
I am with Charlie on the point that there are far better ways to do this than with what would need to be multiple calls to fgetc but if you insist on using that function you would need to run through a loop that evaluates each char. It also does depend on how the data is encoded. If it is ascii (as using a func that returns char would imply) you would check to see if the first char is "-" and then convert each subsequent char to int with atoi(const char*) one at a time, and multiplying your result value by ten each iteration before adding the new value to it. A better way would be to read several chars (using fgets or something) and then convert the char* with atoi(const char*). Maybe if you described more clearly what you were trying to do a better answer could be provided. Beware that using fscanf will fail if your data is not formatted exactly as you specify. But fscanf is really your answer for this problem it seems.
Without over/underflow-check you can use fscanf WITH return-value check:
#include <stdio.h>
int main()
{
int v;
if( 1==fscanf(yourfilepointer, "%d", &v) )
printf ("v = %d\n", v);
else
fputs("error on reading v",stderr);
return 0;
}

Resources