Read 8 Bit Binary Numbers from text File in C - c

I'm trying to read from a text file in C that contains a list of 8 bit binary numbers to be used in another function.
The text file is formatted like:
01101101
10110110
10101101
01001111
11010010
00010111
00101011
Ect. . .
Heres kinda what i was trying to do
Pseudo code
void bincalc(char 8_bit_num){
//does stuff
}
int main()
{
FILE* f = fopen("test.txt", "r");
int n = 0, i = 0;
while( fscanf(f, "%d ", &n) > 0 ) // parse %d followed by a new line or space
{
bincalc(n);
}
fclose(f);
}
I think i'm on the right track, however any help is appreciated.

This is not the standard track to do it, but it ok. You are scanning the file reading ints so it will read the string and interpret them as decimal number, which you should in turn convert to the corresponding binary, i.e. converting 1010 decimal to 2^3+2^1=9 decimal. This is of course possible, you just need to transform powers of ten to powers of 2 (1.10^3+0.10^2+1.10^1+0.10^0 to 1.2^3+0.2^2+1.2^1+0.2^0). Be careful that this work with 8-bits numbers, but not with too huge ones (16-bits will not).
The more common way is to read the strings and decode the strings directly, or read char by char and make an incremental conversion.

If you want to have a number at the end, I would suggest something like the following:
int i;
char buf[10], val;
FILE* f = fopen("test.txt", "r");
while( ! feof(f) ) {
val = 0;
fscanf(f, "%s", buf);
for( i=0; i<8; i++ )
val = (val << 1) | (buf[i]-48);
/* val is a 8 bit number now representing the binary digits */
bincalc(val);
}
fclose(f);
This is just a short snippet to illustrate the idea and does not catch all corner cases regarding the file or buffer handling. I hope it will help anyway.

I think this is a possible solution, i made it simple so you can understand and adapt to your needs. You only need to repeat this for each line.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file =fopen("data","r");
char *result=calloc(1,sizeof(char));
char line[8];
int i=0;
for(;i<8;i++)
{
char get = (char)getc(file);
if(get == '0')
*result <<= 1;
else if(get == '1')
*result = ((*result<<1)|0x1) ;
}
printf("->%c\n",*result);
return 0;
}

I don't know of a way to specify binary format for fscanf() but you can convert a binary string like this.
#include <stdio.h>
#include <stdlib.h>
void fatal(char *msg) {
printf("%s\n", msg);
exit (1);
}
unsigned binstr2int(char *str) {
int i = 0;
while (*str != '\0' && *str != '\n') { // string term or newline?
if (*str != '0' && *str != '1') // binary digit?
fatal ("Not a binary digit\n");
i = i * 2 + (*str++ & 1);
}
return i;
}
int main(void) {
unsigned x;
char inp[100];
FILE *fp;
if ((fp = fopen("test.txt", "r")) == NULL)
fatal("Unable to open file");
while (fgets(inp, 99, fp) != NULL) {
x = binstr2int(inp);
printf ("%X\n", x);
}
fclose (fp);
return 0;
}
File input
01101101
10110110
10101101
01001111
11010010
00010111
00101011
Program output
6D
B6
AD
4F
D2
17
2B

Read the file line by line, then use strtol() with base 2.
Or, if the file is guaranteed to be not long, you could also read the full contents in (dynamically allocated) memory and use the endptr parameter.

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;
}

wzip.c OS three easy steps

I am newbie in OS. Im currently learning OS three easy steps.
I found this code for the the first project of the course.
(wzip) is a file compression tool, and the other (wunzip) is a file decompression tool.
input:
aaaaaaaaaabbbb
correct output:
10a4b
instructions: write out a 4-byte integer in binary format followed by the single character in ASCII.
current output:
ab
I type in the shell:
prompt> gcc -o wzip wzip.c -Wall -Werror
prompt> ./wzip file1.txt > file1.z
This is the link for the project:
https://github.com/remzi-arpacidusseau/ostep-projects/tree/master/initial-utilities
This is the code I found for this specific part of the project:
wzip:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
/*
wzip: is a file compresion tool.
*/
void writeFile(int , char *);
int main(int argc, char *argv[]){
FILE *fp;
char newbuff[2], oldbuff[2];
int count;
if (argc < 2){
printf("wzip: file1 [file2 ...]\n");
exit(EXIT_FAILURE);
}
// open files
for (size_t i = 1; i < argc; i++){
if ((fp = fopen(argv[i], "r")) == NULL){
printf("wzip: cannot open file\n");
exit(EXIT_FAILURE);
}
while (fread(newbuff, 1, 1, fp)){
if (strcmp(newbuff, oldbuff) == 0){
count++;
} else {
if (oldbuff[0] != '\0'){
writeFile(count, oldbuff);
}
count = 1;
strcpy(oldbuff, newbuff);
}
}
fclose(fp);
}
writeFile(count, oldbuff);
return 0;
}
void writeFile(int count, char *oldbuff){
// write as network byte order
count = htonl(count);
fwrite(&count, 4, 1, stdout);
fwrite(oldbuff, 1, 1, stdout);
}
wunzip:
#include <stdio.h>
#include <stdlib.h> // exit
#include <string.h> // memset
#include <arpa/inet.h> // ntohl
int
main(int argc, char *argv[])
{
FILE *fp;
char buff[5];
if (argc <= 1) {
printf("wunzip: file1 [file2 ...]\n");
exit(EXIT_FAILURE);
}
for (size_t i = 1; i < argc; i++) {
if ((fp = fopen(argv[i], "r")) == NULL) {
printf("wunzip: cannot open file\n");
exit(EXIT_FAILURE);
}
int count = 0;
while (fread(&count, 4, 1, fp)) {
count = ntohl(count); // read from network byte order
memset(buff, 0, strlen(buff));
fread(buff, 1, 1, fp);
for (size_t i = 0; i < count; i++) {
printf("%s", buff);
}
}
fclose(fp);
}
return 0;
}
Cant please some one can give a hand to understand better.
Thanks in advance.
How is your solution coming along?
The first that jumps out about the code posted here is that your write the wrong number of bytes. In other words, you don't follow the compression guidelines of the exercise. The instructions for the OSTEP project was to write a 32 bit int (4 bytes) followed by a single ascii character (1 byte).
It helps to set up a test before writing the compressed output. Make sure that what is being written does indeed equal 5 bytes.
#include <stdio.h>
struct token {
u_int32_t count;
u_int8_t ch;
};
size_t numbytes (struct token t) {
/* calculates the number of bytes in a single token */
/* assumes a token has two attributes */
/* should return a value of 5 */
size_t mybytes = sizeof(t.count) + sizeof(t.ch)
return mybytes;
}
I personally found it easier to think about the read procedure in terms of a parser. This is due to the fact that some of the test cases get slightly more complex. You need to effectively manage state between line reads and also between files.
It's a little bit late, but I just did this program for my course's assignment and I want to share my solution. It passes all the available test cases but it's not official from any party (neither from my course nor the project owner).
The code:
#include <stdio.h> // FILE, stdout, fprintf, fwrite, fgetc, EOF, fclose
#include <stdlib.h> // EXIT_*, exit
struct rle_t
{
int l;
char c;
};
void
writerle(struct rle_t rleobj)
{
fwrite((int *)(&(rleobj.l)), sizeof(int), 1, stdout);
fwrite((char *)(&(rleobj.c)), sizeof(char), 1, stdout);
}
struct rle_t
process(FILE *stream, struct rle_t prev)
{
int curr;
struct rle_t rle;
while ((curr = fgetc(stream)) != EOF)
{
if (prev.c != '\0' && curr != prev.c)
{
rle.c = prev.c;
rle.l = prev.l;
prev.l = 0;
writerle(rle);
}
prev.l++;
prev.c = curr;
}
rle.c = prev.c;
rle.l = prev.l;
return rle;
}
int
main(int argc, const char *argv[])
{
if (argc < 2)
{
fprintf(stdout, "wzip: file1 [file2 ...]\n");
exit(EXIT_FAILURE);
}
struct rle_t prev;
prev.c = '\0';
prev.l = 0;
for (int i = 1; i < argc; ++i)
{
FILE *fp = fopen(argv[i], "r");
if (fp == NULL)
{
fprintf(stdout, "wzip: cannot open files\n");
exit(EXIT_FAILURE);
}
struct rle_t rle = process(fp, prev);
prev.c = rle.c;
prev.l = rle.l;
fclose(fp);
}
writerle(prev);
return 0;
}
From the post, I think there is no need to use any function like htonl(3) for this problem. The tricky part is in the writerle() function, which you already got it. But let me explain what I understand:
Use fwrite(3) to write binary format to the stream, in this case, stdout.
First parameter is a pointer, that's why I need &(rleobj.l) and &(rleobj.c).
This line
fwrite((int *)(&(rleobj.l)), sizeof(int), 1, stdout);
tells that I want to write 4 bytes (sizeof(int)) of the first parameter (&(rleobj.l)) to the standard output (stdout) one time (1). The typecast is optional (depending on your compiler and how you want to read your code).
The reason why they require you to do so is because it will separate between the run-length part and the character part.
Let's say you have a simple input file like this:
333333333333333333333333333333333aaaaaaaaaaaa
After encoding without the binary format:
33312a
This is wrong. Because now, it looks like the run-length of the character a is 33312, instead of 33 of 3 and 12 of a.
However, with binary format, those parts are separated:
❯ xxd -b output.z
00000000: 00100001 00000000 00000000 00000000 00110011 00001100 !...3.
00000006: 00000000 00000000 00000000 01100001 ...a
Here, the first four bytes represent the run-length and the next one byte represents the character.
I hope this will help.

Manual "encryption" only outputs 0's to file

My assignment (not homework, just a "try if you can do this" thing) is to use bit operations to encrypt and decrypt a .txt file.
This is the program. It successfully opens files for read/write but puts all 0's and spaces into the output.txt file instead of the expected "encrypted" text. I am guessing the issue comes from a fundamental misunderstanding of either data types or putc(). I understand that it outputs an unsigned char, but my professor said that an unsigned char is nothing but an unsigned int -- not sure if this is purely true or if it was a pedagogical simplification. Thanks a lot for any help.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define NUMARG 3
#define INFILEARG 1
#define OUTFILEARG 2
int main(int argc, char *argv[]){
/* Function prototypes */
unsigned int encryptDecrypt(unsigned int x, unsigned int ed);
const char *get_filename_ext(const char *filename);
FILE *finp;
FILE *foutp;
//ed for encryption/decryption choice
unsigned int ed, c;
const char *ext;
//Check for errors in argument number and file opening.
if(argc != NUMARG){
printf("You have to put the input and output files after the
program name.\n");
return(1);
}
if( (finp = fopen(argv[INFILEARG], "r")) == NULL ){
printf("Couldn't open %s for reading.\n", argv[INFILEARG]);
return(1);
}
if( (foutp = fopen(argv[OUTFILEARG], "w")) == NULL){
printf("Couldn't open %s for writing.\n", argv[OUTFILEARG]);
return(1);
}
//Get and check file extension.
ext = get_filename_ext(argv[INFILEARG]);
if(strcmp(ext, "txt")){
printf("Input file is not a .txt file.\n");
return(1);
}
ext = get_filename_ext(argv[OUTFILEARG]);
if(strcmp(ext, "txt")){
printf("Output file is not a .txt file.\n");
return(1);
}
//Get command to encrypt or decrypt.
do{
printf("Enter e to encrypt, d to decrypt: ");
ed = getchar();
} while(ed != 'e' && ed != 'd');
//Send characters to output file.
while((c = getc(finp)) != EOF ){
putc(encryptDecrypt(c, ed), foutp);
}
// Close files.
if (fclose(finp) == EOF){
printf("Error closing input file.\n");
}
if (fclose(foutp) == EOF){
printf("Error closing output file.\n");
}
if ( ed == 'e'){
printf("Encrypted data written.\n");
} else {
printf("Data decrypted.\n");
}
return 0;
}
const char *get_filename_ext(const char *filename) {
const char *dot = strrchr(filename, '.');
if(!dot || dot == filename) return "";
return dot + 1;
}
unsigned int encryptDecrypt(unsigned int c, unsigned int ed){
if( ed == 'e' ){
printf("%d before operated on.\n", c);
c &= 134;
printf("%d after &134.\n", c);
c ^= 6;
printf("%d after ^6. \n", c);
c <<= 3;
printf("%d after <<3\n", c);
}
else {
c >>= 3;
c ^= 6;
c &= 134;
}
return c;
}
Output:
ZacBook:bitoperations $ cat input1.txt
Please encrypt this message.
ZacBook:bitoperations $ ./encrypt.o input1.txt output.txt
Enter e to encrypt, d to decrypt: e
80 before operated on.
0 after &134.
6 after ^6.
48 after <<3
108 before operated on.
4 after &134.
2 after ^6.
16 after <<3
[...Many more of these debug lines]
2 after &134.
4 after ^6.
32 after <<3
Encrypted data written.
ZacBook:bitoperations $ cat output.txt
00 0 00000 0 0
As you can see, the unsigned int is being operated on successfully. I believe the problem is with putc() but I have tried changing the type of c to char and int and neither have worked.
Your main problem is that &= is a lossy transformation: that is you lose data.
Ditto <<= and >>=, as both cause extreme 1 bits to be lost.
You'll have more luck sticking to XOR; at first at least. That's because x ^ y ^ y is x.
You can eliminate putc &c. by isolating the encryption / decryption processes from the data acquisition stages, and by hardcoding the inputs whilst your getting things working.

Get the length of each line in file with C and write in output file

I am a biology student and I am trying to learn perl, python and C and also use the scripts in my work. So, I have a file as follows:
>sequence1
ATCGATCGATCG
>sequence2
AAAATTTT
>sequence3
CCCCGGGG
The output should look like this, that is the name of each sequence and the count of characters in each line and printing the total number of sequences in the end of the file.
sequence1 12
sequence2 8
sequence3 8
Total number of sequences = 3
I could make the perl and python scripts work, this is the python script as an example:
#!/usr/bin/python
import sys
my_file = open(sys.argv[1]) #open the file
my_output = open(sys.argv[2], "w") #open output file
total_sequence_counts = 0
for line in my_file:
if line.startswith(">"):
sequence_name = line.rstrip('\n').replace(">","")
total_sequence_counts += 1
continue
dna_length = len(line.rstrip('\n'))
my_output.write(sequence_name + " " + str(dna_length) + '\n')
my_output.write("Total number of sequences = " + str(total_sequence_counts) + '\n')
Now, I want to write the same script in C, this is what I have achieved so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
input = FILE *fopen(const char *filename, "r");
output = FILE *fopen(const char *filename, "w");
double total_sequence_counts = 0;
char sequence_name[];
char line [4095]; // set a temporary line length
char buffer = (char *) malloc (sizeof(line) +1); // allocate some memory
while (fgets(line, sizeof(line), filename) != NULL) { // read until new line character is not found in line
buffer = realloc(*buffer, strlen(line) + strlen(buffer) + 1); // realloc buffer to adjust buffer size
if (buffer == NULL) { // print error message if memory allocation fails
printf("\n Memory error");
return 0;
}
if (line[0] == ">") {
sequence_name = strcpy(sequence_name, &line[1]);
total_sequence_counts += 1
}
else {
double length = strlen(line);
fprintf(output, "%s \t %ld", sequence_name, length);
}
fprintf(output, "%s \t %ld", "Total number of sequences = ", total_sequence_counts);
}
int fclose(FILE *input); // when you are done working with a file, you should close it using this function.
return 0;
int fclose(FILE *output);
return 0;
}
But this code, of course is full of mistakes, my problem is that despite studying a lot, I still can't properly understand and use the memory allocation and pointers so I know I especially have mistakes in that part. It would be great if you could comment on my code and see how it can turn into a script that actually work. By the way, in my actual data, the length of each line is not defined so I need to use malloc and realloc for that purpose.
For a simple program like this, where you look at short lines one at a time, you shouldn't worry about dynamic memory allocation. It is probably good enough to use local buffers of a reasonable size.
Another thing is that C isn't particularly suited for quick-and-dirty string processing. For example, there isn't a strstrip function in the standard library. You usually end up implementing such behaviour yourself.
An example implementation looks like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXLEN 80 /* Maximum line length, including null terminator */
int main(int argc, char *argv[])
{
FILE *in;
FILE *out;
char line[MAXLEN]; /* Current line buffer */
char ref[MAXLEN] = ""; /* Sequence reference buffer */
int nseq = 0; /* Sequence counter */
if (argc != 3) {
fprintf(stderr, "Usage: %s infile outfile\n", argv[0]);
exit(1);
}
in = fopen(argv[1], "r");
if (in == NULL) {
fprintf(stderr, "Couldn't open %s.\n", argv[1]);
exit(1);
}
out = fopen(argv[2], "w");
if (in == NULL) {
fprintf(stderr, "Couldn't open %s for writing.\n", argv[2]);
exit(1);
}
while (fgets(line, sizeof(line), in)) {
int len = strlen(line);
/* Strip whitespace from end */
while (len > 0 && isspace(line[len - 1])) len--;
line[len] = '\0';
if (line[0] == '>') {
/* First char is '>': copy from second char in line */
strcpy(ref, line + 1);
} else {
/* Other lines are sequences */
fprintf(out, "%s: %d\n", ref, len);
nseq++;
}
}
fprintf(out, "Total number of sequences. %d\n", nseq);
fclose(in);
fclose(out);
return 0;
}
A lot of code is about enforcing arguments and opening and closing files. (You could cut out a lot of code if you used stdin and stdout with file redirections.)
The core is the big while loop. Things to note:
fgets returns NULL on error or when the end of file is reached.
The first lines determine the length of the line and then remove white-space from the end.
It is not enough to decrement length, at the end the stripped string must be terminated with the null character '\0'
When you check the first character in the line, you should check against a char, not a string. In C, single and double quotes are not interchangeable. ">" is a string literal of two characters, '>' and the terminating '\0'.
When dealing with countable entities like chars in a string, use integer types, not floating-point numbers. (I've used (signed) int here, but because there can't be a negative number of chars in a line, it might have been better to have used an unsigned type.)
The notation line + 1 is equivalent to &line[1].
The code I've shown doesn't check that there is always one reference per sequence. I'll leave this as exercide to the reader.
For a beginner, this can be quite a lot to keep track of. For small text-processing tasks like yours, Python and Perl are definitely better suited.
Edit: The solution above won't work for long sequences; it is restricted to MAXLEN characters. But you don't need dynamic allocation if you only need the length, not the contents of the sequences.
Here's an updated version that doesn't read lines, but read characters instead. In '>' context, it stored the reference. Otherwise it just keeps a count:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h> /* for isspace() */
#define MAXLEN 80 /* Maximum line length, including null terminator */
int main(int argc, char *argv[])
{
FILE *in;
FILE *out;
int nseq = 0; /* Sequence counter */
char ref[MAXLEN]; /* Reference name */
in = fopen(argv[1], "r");
out = fopen(argv[2], "w");
/* Snip: Argument and file checking as above */
while (1) {
int c = getc(in);
if (c == EOF) break;
if (c == '>') {
int n = 0;
c = fgetc(in);
while (c != EOF && c != '\n') {
if (n < sizeof(ref) - 1) ref[n++] = c;
c = fgetc(in);
}
ref[n] = '\0';
} else {
int len = 0;
int n = 0;
while (c != EOF && c != '\n') {
n++;
if (!isspace(c)) len = n;
c = fgetc(in);
}
fprintf(out, "%s: %d\n", ref, len);
nseq++;
}
}
fprintf(out, "Total number of sequences. %d\n", nseq);
fclose(in);
fclose(out);
return 0;
}
Notes:
fgetc reads a single byte from a file and returns this byte or EOF when the file has ended. In this implementation, that's the only reading function used.
Storing a reference string is implemented via fgetc here too. You could probably use fgets after skipping the initial angle bracket, too.
The counting just reads bytes without storing them. n is the total count, len is the count up to the last non-space. (Your lines probably consist only of ACGT without any trailing space, so you could skip the test for space and use n instead of len.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
FILE *my_file = fopen(argv[1], "r");
FILE *my_output = fopen(argv[2], "w");
int total_sequence_coutns = 0;
char *sequence_name;
int dna_length;
char *line = NULL;
size_t size = 0;
while(-1 != getline(&line, &size, my_file)){
if(line[0] == '>'){
sequence_name = strdup(strtok(line, ">\n"));
total_sequence_coutns +=1;
continue;
}
dna_length = strlen(strtok(line, "\n"));
fprintf(my_output, "%s %d\n", sequence_name, dna_length);
free(sequence_name);
}
fprintf(my_output, "Total number of sequences = %d\n", total_sequence_coutns);
fclose(my_file);
fclose(my_output);
free(line);
return (0);
}

To generate hexadecimal numbers for 1000 bytes in 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.

Resources