How to get hex values from string? - c

I have a function with an input parameter "text" , which consists of a string containing unknown number of 2-character Hexadecimal numbers separated by space. I need to read them and put them in separate array indexes or read them in for loop and work with them one by one. Each of these values represents an encrypted char(the hex values are ascii values of the characters). How could i do that? I think i should use sscanf(); but i can't figure out how to do it.
char* bit_decrypt(const char* text){
int size=strlen(text)/3;
unsigned int hex[size];
char*ptr;
for(int i=0; i<size+1; i++){
hex[i] = strtoul(text, &ptr, 16);
printf("%x ",hex[i]);
}
return NULL;
}
output is: "80 80 80 80 80 80 80 80 80 80 80 80"
should be: "80 9c 95 95 96 11 bc 96 b9 95 9d 10"

You scan always the first value of text, because you forgot to move the input for strtoul right after the end of the previous scan. That's what the **end-parameter of strtoul is good for: it points to the character right after the last digit of a successful scan. Note: if nothing could have been read in, the end-pointer is equal the input pointer, and this indicates a "wrongly formated number" or the end of the string. See the following program illustrating this. Hope it helps.
int main() {
const char* input = "80 9c 95 95 96 11 bc 96 b9 95 9d 10";
const char *current = input;
char *end = NULL;
while (1) {
unsigned long val = strtoul(current, &end, 16);
if (current == end) // invalid input or end of string reached
break;
printf("val: %lX\n", val);
current = end;
}
}

This is also possible solution with the use of strchr, and strtoul(tmp,NULL,16);
In your solution remember that size_t arr_len = (len/3) + 1; since the last token is only 2 bytes long.
Input text tokens are converted to bytes and stored in char array:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char text[] = "80 9c 95 95 96 11 bc 96 b9 95 9d 10";
size_t len = strlen(text);
size_t arr_len = (len/3) + 1;
printf("len= %zu arr_len= %zu\n", len, arr_len);
printf("Text:\n%s\n", text);
char array[arr_len];
const char *p1 = text;
char tmp[3];
tmp[2] = 0;
printf("Parsing:\n");
for(size_t i=0; i< arr_len; i++)
{
p1 = strchr(p1,' ');
if(p1)
{
tmp[0] = *(p1-2);
tmp[1] = *(p1-1);
array[i]= (char)strtoul(tmp,NULL,16);
printf("%2x ", (unsigned char) array[i]);
p1++;
if(strlen(p1) == 2 ) // the last char
{
i++;
tmp[0] = *(p1);
tmp[1] = *(p1+1);
array[i]= (char)strtoul(tmp,NULL,16);
printf("%2x", (unsigned char) array[i]);
}
}
}
printf("\nArray content:\n");
for(size_t i=0; i< arr_len; i++)
{
printf("%2x ", (unsigned char) array[i]);
}
return 0;
}
Test:
len= 35 arr_len= 12
Text:
80 9c 95 95 96 11 bc 96 b9 95 9d 10
Parsing:
80 9c 95 95 96 11 bc 96 b9 95 9d 10
Array content:
80 9c 95 95 96 11 bc 96 b9 95 9d 10

Related

How can I read a file integer by integer and put them into a 2D array?

I am trying to read all the numbers from a txt file and put them into a 2D array. I shouldn't worry about the size and stuff because I know it will be entered in 9 rows and in each row there will be 9 numbers. But if I run this code I get the following output.
int main() {
FILE *fpointer = fopen("filename.txt", "r");
int ch;
int arr[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
ch = fgetc(fpointer);
arr[i][j] = ch;
//printf("%d", ch);
}
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
fclose(fpointer);
return 0;
}
Output:
49 51 52 53 54 55 48 57 50
10 52 50 49 57 56 51 55 52
49 10 51 49 50 52 57 56 55
49 51 10 52 50 51 53 49 51
53 49 49 10 50 51 52 54 51
53 55 50 49 10 53 50 51 54
55 56 50 52 53 10 54 52 54
53 56 57 51 50 49 10 53 52
57 50 57 56 51 53 54 10 50
But the entered numbers are:
134567092
421983741
312498713
423513511
234635721
523678245
646589321
549298356
234698721
I assume it maybe have to do something with the fgets() function, but I tried to use getw(), but then I get even worse numbers. Maybe it tries to read the file in hexadecimals or something. Any ideas?
I'm not totally sure what behavior you were hoping for here, but I recommend decoding the ASCII digits before you store the numbers in your array, like this:
arr[i][j] = ch - '0';
Also, note that fgetc will return line-ending bytes like 10, because those are characters in your file too, even if they are not exactly visible. So when you receive one of those, you need to discard it and call fgetc again. Or you could insert an extra fgetc call at the end of each line (right after your j loop) to read those.
Looks like you need to convert the char from an ascii representation of the digit, into the actual digit. See also: Convert a character digit to the corresponding integer in C
So this part:
for(int j =0; j<9;j++){
ch = fgetc(fpointer);
arr[i][j] = ch;
//printf("%d", ch);
}
Would become this:
for(int j =0; j<9;j++){
ch = fgetc(fpointer);
if(isdigit(ch)) {
ch = ch - '0';
} else {
printf("error: Non-digit found!\n");
exit(1);
}
arr[i][j] = ch;
//printf("%d", ch);
}

How to copy the semester[20] string under the structure, and count and print it in my output

I don't want to hard code fall19 and spring19 into the output. I want whatever the user input into the array semester[20] under the structure be counted and inputted into the printf. (The inputs are in a text file named enrollment.txt)
Here is the text file for enrollment.txt
10 c1 fall19 80
10 c2 fall19 85
10 c3 fall19 95
40 c2 fall19 65
2 c1 fall19 70
40 c4 fall19 95
40 c5 fall19 85
2 c2 fall19 50
4 c4 spring19 95
4 c5 spring19 89
13 c1 spring19 99
13 c2 spring19 75
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct Enrollment {
int stud_id;
char course_id[5];
char semester[20];
float score;
}; // end struct Enrollment
struct Enrollment enroll[50];
int count1 = 0;
int count2 = 0;
for (int i = 0; i < 15; i++) {
if (strcmp(enroll[i].semester, "fall19") == 0) {
count1++;
} else if (strcmp(enroll[i].semester, "spring19") == 0) {
count2++;
}
}
printf("\n%s %d", "fall19", count1);
printf("\n%s %d", "spring19", count2);
printf("\n------------------");
printf("\n==================");
printf("\n------------------");
}
}
}
return 0;
}
Example output:
fall19 8
spring19 4
summer19 0
In your code, i do not see your function, i think you forget main, right ? if it's typo, you can see my idea below:
Firstly, you have to store data from enrollment.txt into array enroll[50];.
For this task, you can get line by line of text file using fgets or getline function. For exmaple:
FILE *fp = fopen("enrollment.txt", "r");
if(!fp) {//handle error};
char line[256];
int i = 0;
while(line, sizeof(line), fp) {
// using sscanf to read data from line to array
}
fclos(fp);
For reading the data from line, you can use sscanf:
int err = sscanf("%d %s %s %f\n", &enroll[i].stud_id, enroll[i].course_id, enroll[i].semester, &enroll[i].score);
if(err != 4) {//handle the error}
i++;
Then you can use for loop from 0 to i to increase count1 and count2 as your code.

How can I take the average of only certain rows and columns of a 2D array?

I have to take the average of only the test grades and put them into the last column but I have no idea how to do it. I have the function for the 2D array that takes in a filename that contains the grades but the first column is the student id so I don't need to take the average of that.
This is the code I have for the 2D array function.
#define x 10
#define y 6
void getData(float arr1[x][y])
{
FILE* graFile;
float arr2[x][y];
char userIn[50];
printf("Enter the text filename: ");
scanf("%s", userIn);
graFile = fopen(userIn, "r");
int studentId, test1, test2, test3, test4;
for(int i = 0; i < x; i++)
{
if(graFile != NULL)
{
fscanf(graFile, "%d%d%d%d%d", &studentId, &test1, &test2, &test3, &test4);
arr2[i][0] = studentId;
arr2[i][1] = test1;
arr2[i][2] = test2;
arr2[i][3] = test3;
arr2[i][4] = test4;
}
else
{
printf("\nThis file does not exist.");
return;
}
}
printf("\n %11s%11s%11s%11s%11s%11s", "Student Id","Test 1","Test 2","Test 3","Test 4","Final\n");
printf("*********************************************************************\n");
for(int i = 0; i < x; i++)
{
for(int j = 0; j < y; j++)
{
printf("%11.0f", arr2[i][j]);
}
printf("\n");
}
printf("*********************************************************************\n");
fclose(graFile);
return;
}
That gives me this output
Enter the text filename: grades.txt
Student Id Test 1 Test 2 Test 3 Test 4 Final
*********************************************************************
6814 85 86 92 88 0
7234 76 81 84 78 0
6465 87 54 68 72 0
7899 92 90 88 86 0
9901 45 78 79 80 0
8234 77 87 84 98 0
7934 76 91 84 65 0
7284 56 81 87 98 0
7654 76 87 84 88 0
3534 86 81 84 73 0
*********************************************************************
Now I just need to create a new function that averages the test grades from this array and put it into the last column but I'm having trouble doing that. I appreciate any help I can get.
void setAverage(float arr[][y], int x) {
for(int i = 0; i < x; i++) {
arr[i][5] = (arr[i][1] + arr[i][2] + arr[i][3] + arr[i][4]) / 4;
}
}

Trying to print out useful data from Memory

void update_memblock(MEMBLOCK *mb)
{
static unsigned char tempbuf[128 * 1024];
SIZE_T bytes_left;
SIZE_T total_read;
SIZE_T bytes_to_read;
SIZE_T bytes_read;
bytes_left = mb->size;
total_read = 0;
while (bytes_left)
{
bytes_to_read = (bytes_left > sizeof(tempbuf)) ?
sizeof(tempbuf) : bytes_left;
ReadProcessMemory(mb->hProc, mb->addr + total_read,
tempbuf, bytes_to_read, &bytes_read);
if (bytes_read != bytes_to_read) break;
memcpy(mb->buffer + total_read, tempbuf, bytes_read);
bytes_left -= bytes_read;
total_read += bytes_read;
}
mb->size = total_read;
}
This is the current code I have, I am initially reading another process' memory using ReadProcessMemory. Now I have the temporary data stored in tempbuf. I am able to output the data from tempbuf in hexadecimal form. But I was planning to display it as shown in the picture, also another complexity I'm facing here is if bytes_left > sizeof(tempbuf) I'm only reading enough data equivalent to the size of tempbuf. How do I read more data as the array I defined can only support as much data?
If I understand correctly, your main question is about how to mimic the output from hex editors.
This can be broken up into 3 parts:
Printing the address
Printing the hex value of each byte
Printing the ASCII value for each byte
Printing an address in hex is easy. We can use %p to print the address of a pointer like this:
char* mem = malloc(99);
printf("%p\n", (void*)mem);
// output: 0xc17080
Next you can print the hex value of a byte using %02x on a char (1 byte). The 02 specifies a zero padded field width of 2. In this case it's just to make 0 print as 00 to make things line up and look pretty.
printf("%02x", mem[0]);
// output: 0A
Lastly, printing ASCII is the easiest of all... almost. We can use %c to print a byte for some ASCII values, but we don't want to print things like \nor \t. To solve this we can limit the use of %c to the character/symbol region of the ASCII table and print . for everything else.
char c = mem[0];
if ( ' ' <= c && c <= '~' ) {
printf("%c", c);
}
else {
printf(".");
}
//output: .
Now we just need to combine these all together. You can decide how many bytes you want to display per line and print "[address] [n hex bytes] [n ascii bytes]" and repeat until you've gone through the entire memory region. I've given a sample function below and you can run it for yourself here.
void display_mem(void* mem, int mem_size, int line_len) {
/*
mem - pointer to beggining of memory region to be printed
mem_size - number of bytes mem points to
line_len - number of bytyes to display per line
*/
unsigned char* data = mem;
int full_lines = mem_size / line_len;
unsigned char* addr = mem;
for (int linno = 0; linno < full_lines; linno++) {
// Print Address
printf("0x%x\t", addr);
// Print Hex
for (int i = 0; i < line_len; i++) {
printf(" %02x", data[linno*line_len + i]);
}
printf("\t");
// Print Ascii
for (int i = 0; i < line_len; i++) {
char c = data[linno*line_len + i];
if ( 32 < c && c < 125) {
printf(" %c", c);
}
else {
printf(" .");
}
}
printf("\n");
// Incremement addr by number of bytes printed
addr += line_len;
}
// Print any remaining bytes that couldn't make a full line
int remaining = mem_size % line_len;
if (remaining > 0) {
// Print Address
printf("0x%x\t", addr);
// Print Hex
for (int i = 0; i < remaining; i++) {
printf(" %02x", data[line_len*full_lines + i]);
}
for (int i = 0; i < line_len - remaining; i++) {
printf(" ");
}
printf("\t");
// Print Hex
for (int i = 0; i < remaining; i++) {
char c = data[line_len*full_lines + i];
if ( 32 < c && c < 125) {
printf(" %c", c);
}
else {
printf(" .");
}
}
printf("\n");
}
}
Sample output:
0x1e79010 74 65 73 74 79 2a 6e t e s t y * n
0x1e79017 0c 3e 24 45 5e 33 27 . > $ E ^ 3 '
0x1e7901e 18 51 09 2d 76 7e 4a . Q . - v . J
0x1e79025 12 53 0f 6e 0b 1a 6d . S . n . . m
0x1e7902c 31 6e 03 2b 01 2f 2c 1 n . + . / ,
0x1e79033 72 59 1c 76 18 38 3c r Y . v . 8 <
0x1e7903a 6e 6b 5b 00 36 64 25 n k [ . 6 d %
0x1e79041 2d 5c 6f 38 30 00 27 - \ o 8 0 . '
0x1e79048 33 12 15 5c 01 18 09 3 . . \ . . .
0x1e7904f 02 40 2d 6c 1a 41 63 . # - l . A c
0x1e79056 2b 72 18 1a 5e 74 12 + r . . ^ t .
0x1e7905d 0d 51 38 33 26 28 6b . Q 8 3 & ( k
0x1e79064 56 20 0b 0b 32 20 67 V . . . 2 . g
0x1e7906b 34 30 68 2e 70 0f 1c 4 0 h . p . .
0x1e79072 04 50 . P
As for the second part of your question, if you cannot increase the size of tempbuf then you are stuck dealing with that amount of memory at any moment in time.
However, if all you want to do is display the memory as described above you can display each section of memory in chunks. You can get a chunk of memory, display it, then get a new chunk, display the new chunk, repeat.
Something along the lines of
while (bytes_left) {
ReadProcessMemory(mb->hProc, mb->addr + total_read, tempbuf, bytes_to_read, &bytes_read);
// Get new chunk
memcpy(mb->buffer + total_read, tempbuf, bytes_read);
// Display chunk
display_mem(tempbuf, bytes_read);
bytes_left -= bytes_read;
}
You will need to do a little more work to check for errors and make everything look nice but hopefully that gives you a good idea of what could be done.
There is no way to store more data than you have space allocated. If you need to store more data, you will need to allocate more space somewhere (more RAM, a disk file, etc). Compression will allow you to store a bit more data in the space allocated, but you aren't going to gain all that much. For virtually unlimited storage, you are going to need to write to disk.
Alternatively, if you just need to display once and then can forget, read in 16 bytes, display the line, and then read the next 16 bytes into the same memory.

C turning char arrays into int behaving weird

I have a much longer char array that I am turning into integers, but I cannot figure out why it behaves weird in some spots.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char x[60] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
printf("%lu\n\n", strlen(x));
for ( int i = 0; i < strlen(x); i+=3 ) {
char num[2];
num[0] = (char)x[i];
num[1] = (char)x[i+1];
printf("%d, ", atoi(num));
}
}
The Output:
8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 500, 773, 916, 89,
Everything is great until.....500, 773, 916, 89...what is happening?
As you can see atoi wants a C-String: a null terminated array of character.
So, this
char num[2];
num[0] = (char)x[i];
num[1] = (char)x[i+1];
Have to be
char num[3] = {0};
num[0] = (char)x[i];
num[1] = (char)x[i+1];
num[2] = '\0'; // this could be avoided in your specific case
The need for a proper string with its null character has been posted by many.
Just wanted to add another coding idea: compound literal. (char[]) { x[i], x[i + 1], '\0' } to implement that.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char x[] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
size_t len = strlen(x);
printf("%zu\n\n", len);
for (size_t i = 0; i < len; i += 3) {
printf("%d, ", atoi((char[] ) { x[i], x[i + 1], '\0' }));
}
}
Output
59
8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8,
Some other fixes made too.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char num[3]; // 3rd byte is the null character
num[3]='\0';
char x[60] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
printf("%lu\n\n", strlen(x));
for ( int i = 0; i < strlen(x); i+=3 ) {
strncpy ( num, x+i, 2 ); // Copies two characters starting from x+i
// You get a null terminated string num here.
printf("%d, ", atoi(num));
}
printf("\n");
}
num[0] = (char)x[i];
num[1] = (char)x[i+1];
printf("%d, ", atoi(num)
This assumes that the number of digits in your input will always be 2(for which num should be declared as char num[3]. Do a dry run of your logic with a smaller input set, for eg:"01 50"
i=0
num[0] = *(num+0) = 0
num[1] = *(num+1) = <space>
num[2] = *(num + 2) = ????? Since this memory is not allocated for num
printf("%d, ", atoi("1<space>")) = 1 (atoi stops after looking at num[1] which is a non-digit character)
i = 3
num[0] = *(num+0) = 0
num[1] = *(num + 1) = 0
num[2] = *(num + 2) = ?????
printf("%d ", atoi("00<garbage>...")) // this is UB since atoi will definitely read memory at `(num + 2)` which is beyond the bounds of what the compiler allocated for it.
Try using sscanf to parse the input rather than relying on the number of digits. That would be much more cleaner and less prone to errors.
int main ()
{
char x[60] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
const char *y = x;
char outputBuffer[10];
for(;sscanf(y, "%s", outputBuffer) > 0; y+=strlen(outputBuffer)) printf("%d, ", atoi(outputBuffer));
}
The answer to your question has already been provided, i.e. that a C string is by definition a NULL terminated char array. Without room for the NULL terminator, at best the results from a string passed to a string function cannot be trusted.
I am offering this just to highlight some additional ideas on reading a char array into int array, where the NULL terminator becomes almost a non-issue.
The following method includes simple string parsing and dynamic memory usage, where the string contents get read directly into int memory, bypassing any need for an intermediate string buffer, resulting in the ability to read any legal integer length from the string, and convert directly into int:
see inline comments for suggestions:
int main(void)
{
//leave array index blank, the compiler will size it for you
char x[] = "08 0223 22 97 382345 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 1000";
// ^
int size = sizeof(x)/sizeof(x[0]);//use sizeof macro to get number of elements in array
char *tok = NULL;
int i = 0;
int count=0;
for(i=0;i<size;i++)
{
if(x[i]==' ')count++;//get count to size int array
}
int *array = malloc((count+1)*sizeof(int));
if(array)
{
i=0;//reinitialize to 0 for use here
tok = strtok(x, " \n");
while(tok)//test after each parse before processing
{
if((i>0)&&(i%6==0))printf("\n");//newlines to format
array[i++] = atoi(tok);
printf("%6d, ", array[i]);
// ^ provide spacing in output
tok = strtok(NULL, " \n");
}
free(array);
}
return 0;
}

Resources