Convert array of hex values to corresponding ascii characters - c

I want to convert an array of hexadecimal numbers to their corresponding ascii character?
For eg:
arr_hex[] = {6,1,6,2,6,5,6,A,7,A}
to
arr_ascii[] = {a,b,e,j,z}

#include <stdio.h>
#define A 10
#define B 11
#define C 12
#define D 13
#define E 14
#define F 15
int main(void){
int arr_hex[] = {6,1,6,2,6,5,6,A,7,A};
int size = sizeof(arr_hex)/sizeof(*arr_hex);
char arr_ascii[size/2];
int i, j;
for(j=i=0; j < size/2; i+=2){
printf("%c", arr_ascii[j++] = arr_hex[i]*16 + arr_hex[i+1]);
}
printf("\n");
return 0;
}

Related

Write a program to check the number of the same characters of a given string for every ASCII value

I am getting a to z counts but I want their count too: (, ", -, ,...
#include <stdio.h>
int letter_counter(char* str, char c)
{
int i,counter=0;
for(i=0;str[i]!= 0;i++)
{
if (str[i] == c)
counter++;
}
return counter;
}
int main()
{
char str[] ="Write a function that takes a character and a string, and returns the index of that character in the string (or -1 if the character is not found)";
char c;
for(c = 'a';c<='z';c++)
{
printf(" %c --- %d\n",c,letter_counter(str,c));
}
}
Output:
a --- 14
b --- 0
c --- 7
d --- 4
e --- 10
f --- 4
g --- 2
h --- 8
i --- 8
j --- 0
k --- 1
l --- 0
m --- 0
n --- 11
o --- 5
p --- 0
q --- 0
r --- 12
s --- 5
t --- 17
u --- 3
v --- 0
w --- 0
x --- 1
y --- 0
z --- 0
You can try something like this.
I've just basically changed your for loop to not only go from 'a' to 'z' but from ASCII 32 (space) to ASCII 127 (you can check an ASCII table here, for example: https://theascii.com/wp-content/uploads/2020/05/Basic-ASCII-table-image.png). Notice this will just work for plain text, using ASCII values below 128 (e.g. not for Unicode).
#include <stdio.h>
int letter_counter(char* str, char c)
{
int counter = 0;
for(int i = 0; str[i] != 0; ++i)
{
if (str[i] == c)
{
counter++;
}
}
return counter;
}
int main()
{
char str[] = "Write a function that takes a character and a string,"
" and returns the index of that character in the string "
" (or -1 if the character is not found)";
for (char c = 32; c < 127; ++c)
{
int count = letter_counter(str, c);
if (count)
{
printf(" %c --- %d\n", c, count);
}
}
}
Online demo: https://godbolt.org/z/6TqvnMrqh
#include <stdio.h>
#include <limits.h>
#include <stdint.h>
int main(void) {
char* text = "Write a program to check the number of the same characters of a given string for every ASCII value getting a to z counts but I want their count too: (, \", -, ,...";
size_t count[CHAR_MAX] = {0};
while(*text)
{
count[*text++]++;
}
for(int i=0; i<CHAR_MAX; ++i)
{
if (count[i])
{
printf("%c : %d\n", i, count[i] );
}
}
return 0;
}

What are these numbers that convert to text?

/***
* Author: Omar IRAQI
*/
#include <stdio.h>
#include <stdlib.h>
#define N 11
int main(void) {
int i, *p, encoded_message[] = {1634558290, 544104804, 1701994827, 539782501, 1918985572,
1970565920, 1953391972, 1226845811, 1936289056, 1870209139, 8565};
char *message;
printf("%s\n", (char*)encoded_message);
/**
* Let's say it again!
*/
message = (char*)malloc(N * sizeof(int));
p = (int*)message;
for (i=0; i < N; i++, p++)
*p = encoded_message[i];
printf("%s\n", message);
return 0;
}
this outputs the message twice:
Ramadan Kareem, dear students. I miss you!
I was wondering what these encoded numbers are since they don't match with ASCII code
Each int should be split into 4 bytes to recover the individual ascii codes. You could simply print each int as hex.
You can also calculate:
1634558290 % 256
(1634558290 >> 8) % 256
(1634558290 >> 16) % 256
and so on.
You have 11 x 4 byte integers for a total of 44 bytes. This corresponds closely to the length of the message.
1 634 558 290 = 0x616D6152
52 : R
61 : a
6D : m
61 : a
Lookup little endian vs big endian for why the bytes are inverted.

Binary to decimal algorithm in c giving strange results

Hi i'm fairly new to c but for a program I'm writing I need to convert binary strings to decimal numbers. here is my current code:
int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++)
{
if(binaryString[i] == '1')
decimal += 2^((len - 1) - i);
printf("i is %i and dec is %i and the char is %c but the length is %i\n", i, decimal, binaryString[i], len);
}
return decimal;
}
int main(int argc, char **argv)
{
printf("%i", BinaryToInt("10000000"));
}
and here is the output:
i is 0 and dec is 5 and the char is 1 but the length is 8
i is 1 and dec is 5 and the char is 0 but the length is 8
i is 2 and dec is 5 and the char is 0 but the length is 8
i is 3 and dec is 5 and the char is 0 but the length is 8
i is 4 and dec is 5 and the char is 0 but the length is 8
i is 5 and dec is 5 and the char is 0 but the length is 8
i is 6 and dec is 5 and the char is 0 but the length is 8
i is 7 and dec is 5 and the char is 0 but the length is 8
5
I'm confused as to why this doesn't work, all help is greatly appreciated. Thanks in advance!
Ps: I'm used to java so at the moment C just makes me cry
The ^ operator is not for exponentiation, but is instead the bitwise XOR operator.
If you want to raise a number to a power of 2, use the left shift operator << to shift the value 1 by the exponent in question.
decimal += 1 << ((len - 1) - i);
The trick is the same as with any number base: for each incoming digit, multiply the accumulator by the number base and add the digit.
#include <stdio.h>
#include <string.h>
int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++) {
decimal = decimal * 2 + binaryString[i] - '0';
}
return decimal;
}
int main(void)
{
printf("%d", BinaryToInt("10000000"));
return 0;
}
Program output:
128

use of rand function to assign a value randomly [duplicate]

This question already has answers here:
How to create a random permutation of an array?
(3 answers)
Closed 6 years ago.
i am doing a homework. i put rand function in a loop.
int counter = 1;
while ( counter <= 10 ){
variable1 = rand() % 5 + 1;
printf("%d", variable);
counter = counter + 1;
In this code, rand function assigns different value to variable called variable1 but sometimes it assigns same value because range of rand function is narrow. how can i perform that rand function assign different number to variable at the time when loop returns every time.
While rand() is not the greatest random function it should do the trick for many jobs and certainly for most homework. It is perfectly valid to have the same number returned twice in a row from a random function -- as the function should not have any memory of what values were previously returned.
The best way to understand this, is with an example of a coin-toss. Every coin toss is random, and the coin has no memory of the previous toss, so it is possible to flip a coin 32 times in a row and they all comes up head -- if every coin toss is a bit in a 32 bit integer you have created the binary value of integer zero.
However human tend to think (intuition) that having the same value returned more than once is "wrong" for a random function -- but our intuition is wrong on this account.
If you for some reason do want to not repeat the number from one loop to the next, then you will need to program that regardless of which random functions you use -- since any random function would be capable of returning the same values twice.
So something like this would do it;
int counter = 1;
int prevValue = -1;
while ( counter <= 10 ){
do {
variable1 = rand();
} while (variable1 == prevValue);
prevValue = variable1;
variable1 = variable1 % 5 + 1;
printf("%d", variable);
counter = counter + 1;
}
Note that this is still capable of printing the same value twice, since 10 and 15 would be different values before the %5 but would be the same after. If you want the %5 to be taken into account, so the printf never print the same value twice in a row, you would need to move the %5 inside the loop.
In your code snippet i can't find which instruction is the last one inside while. If you want to get different numbers every program run you should use srand() function before while.
But as you mentioned before. Your range (1 - 5) is to narrow to get 10 unique values every time.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int counter = 1;
int variable1 = 0;
srand(time(NULL));
while ( counter <= 10 ) {
variable1 = rand() % 5 + 1;
printf("%d ", variable1);
counter = counter + 1;
}
putchar('\n');
return 0;
}
how can i perform that rand function assign different number to variable at the time when loop returns every time?
I take this to mean OP does not want to generate the same number twice in a row.
On subsequent iterations, use %(n-1)
int main(void) {
int counter;
int variable;
for (counter = 1; counter <= 10; counter++) {
// First time in loop
if (counter <= 1) {
variable = rand() % 5 + 1;
} else {
int previous = variable;
variable = rand() % (5 - 1) + 1;
if (variable >= previous) variable++;
}
printf("%d\n", variable);
}
return 0;
}
In order to generate a unique list of random numbers, you must check each number generated against the list of numbers previously generated to insure there is no duplicate. The easiest way is to store your previously generated numbers in an array to check against. Then you simply iterate over the values in the array, and if your most recent number is already there, create a new one.
For example, you can use a simple flag to check if your are done. e.g.
while (counter < MAXI){
int done = 0;
while (!done) { /* while done remains 0 (not done) */
done = 1;
tmp = rand() % MAXI + 1; /* generate radom number */
for (i = 0; i < counter; i++) /* check again previous */
if (tmp == array[i]) /* if num already exists */
done = 0; /* set as (not done) */
}
array[counter++] = tmp; /* assign random value */
}
Or you can use the old faithful goto to do the same thing:
while (counter < MAXI) {
gennum:
tmp = rand() % MAXI + 1;
for (i = 0; i < counter; i++)
if (tmp == array[i])
goto gennum;
array[counter++] = tmp;
}
Whichever makes more sense to you. Putting together a full example, you could do:
#include <stdio.h>
#include <stdlib.h> /* for rand */
#include <time.h> /* for time */
enum { MAXI = 10 };
int main (void) {
int array[MAXI] = {0}, counter = 0, i, tmp;
srand (time (NULL)); /* initialize the semi-random number generator */
while (counter < MAXI){
int done = 0;
while (!done) { /* while done remains 0 (not done) */
done = 1;
tmp = rand() % MAXI + 1; /* generate radom number */
for (i = 0; i < counter; i++) /* check again previous */
if (tmp == array[i]) /* if num already exists */
done = 0; /* set as (not done) */
}
array[counter++] = tmp; /* assign random value */
}
for (i = 0; i < MAXI; i++)
printf (" array[%2d] = %d\n", i, array[i]);
return 0;
}
(note: the number your mod (%) the generated number by must be equal to or greater than the number of values you intend to collect -- otherwise, you cannot generate a unique list.)
Example Use/Output
$ ./bin/randarray
array[ 0] = 8
array[ 1] = 2
array[ 2] = 7
array[ 3] = 9
array[ 4] = 1
array[ 5] = 4
array[ 6] = 3
array[ 7] = 10
array[ 8] = 6
array[ 9] = 5
A Shuffled Sequence
Given the discussion in the comments, a good point was raised concerning whether your goal was to create unique set of random numbers (above) or a random set from a sequence of numbers (e.g. any sequence, say 1-50 in shuffled order). In the event you are looking for the latter, then an efficient method to create the shuffled-sequence is using a modified Fisher-Yates shuffle knows as The "inside-out" algorithm.
The algorithm allows populating an uninitialized array with a shuffled sequence from any source of numbers (whether the source can be any manner of generating numbers). Essentially, the function will swap the values within an array at the current index with the value held at a randomly generated index. An implementation would look like:
/** fill an uninitialized array using inside-out fill */
void insideout_fill (int *a, int n)
{
int i, val;
for (i = 0; i < n; i++) {
val = i ? randhq (i) : 0;
if (val != i)
a[i] = a[val];
a[val] = i; /* i here can be any source, function, etc.. */
}
}
(where randhq is any function that generates a random value (0 <= val < n))
A short example program that uses the function above to generate a shuffled array of value from 0 - (n-1) is shown below. The example generates a shuffled sequence of values in array using the inside-out algorithm, and then confirms the sequence generation by sorting the array:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void insideout_fill (int *a, int n);
int randhq (int max);
void prnarray (int *a, size_t n, size_t strd, int wdth);
int intcmp (const void *a, const void *b);
int main (int argc, char **argv) {
srand (time (NULL));
int arrsz = argc > 1 ? (int)strtol (argv[1], NULL, 10) : 50;
int array[arrsz];
insideout_fill (array, arrsz);
printf ("\n array initialized with inside-out fill:\n\n");
prnarray (array, arrsz, 10, 4);
qsort (array, arrsz, sizeof *array, intcmp);
printf ("\n value confirmation for inside-out fill:\n\n");
prnarray (array, arrsz, 10, 4);
return 0;
}
/** fill an uninitialized array using inside-out fill */
void insideout_fill (int *a, int n)
{
int i, val;
for (i = 0; i < n; i++) {
val = i ? randhq (i) : 0;
if (val != i)
a[i] = a[val];
a[val] = i; /* i here can be any source, function, etc.. */
}
}
/** high-quality random value in (0 <= val <= max) */
int randhq (int max)
{
unsigned int
/* max <= RAND_MAX < UINT_MAX, so this is okay. */
num_bins = (unsigned int) max + 1,
num_rand = (unsigned int) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
int x;
/* carefully written not to overflow */
while (num_rand - defect <= (unsigned int)(x = rand()));
/* truncated division is intentional */
return x/bin_size;
}
/** print array of size 'n' with stride 'strd' and field-width 'wdth' */
void prnarray (int *a, size_t n, size_t strd, int wdth)
{
if (!a) return;
register size_t i;
for (i = 0; i < n; i++) {
printf (" %*d", wdth, a[i]);
if (!((i + 1) % strd)) putchar ('\n');
}
}
/** qsort integer compare */
int intcmp (const void *a, const void *b)
{
return *((int *)a) - *((int *)b);
}
Example Use/Output
$ ./bin/array_io_fill
array initialized with inside-out fill:
40 15 35 17 27 28 20 14 32 39
31 25 29 45 4 16 13 9 49 7
11 23 8 33 48 37 41 34 19 38
24 26 47 44 5 0 6 21 43 10
2 1 18 22 46 30 12 42 3 36
value confirmation for inside-out fill:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
Look it over and let me know if you have any questions.

Read integers from stdin and store in 2d array (C)

I'm trying to read a text file containing integers via stdin and store the values in a 9x9 array (please note that the file must be read via stdin and not as an arg)
This is what I have:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
int puzzle[9][9];
int i,j,count=0;
char value[81];
for( i = 0; i < 9; i++ ) {
for( j = 0; j < 9; j++ ) {
scanf("%c", &value[count]);
puzzle[i][j] = value[count] - '0';
count++;
}
}
}
But it doesn't seem to convert the ASCII characters from scanf to int, which is what I thought the value[count] - '0' was supposed to do, so I end up getting values like this:
-16-16-160-16-160-16-161
Basically i'm trying to do exactly whats described in this thread, but in C instead of C++:
How to convert a 2d char array to a 2d int array?
Edit -
The input file looks like this (contains both white space and new lines):
0 0 1 9 0 0 0 0 8
6 0 0 0 8 5 0 3 0
0 0 7 0 6 0 1 0 0
0 3 4 0 9 0 0 0 0
0 0 0 5 0 4 0 0 0
0 0 0 0 1 0 4 2 0
0 0 5 0 7 0 9 0 0
0 1 0 8 6 0 0 0 7
7 0 0 0 0 9 2 0 0
The problem is not with the conversion line puzzle[i][j] = value[count] - '0';. The problem lies with the following scanf() statement, scanf("%c", &value[count]);. The scanf is reading the first white space. Use scanf(" %c", &value[count]); to read the input.
%c does eactly what it should: it reads one character. D'oh, it's whitespace? That doesn't matter. This is why...
... you shouldn't use %c but %d for scanning integers;
...you shouldn't use scanf() at all for something simple like this.
What I'd do if I were you:
int matrix[9][9];
int i = 0;
char buf[0x100];
while (fgets(buf, sizeof(buf), stdin)) {
char *end;
char *p = strtok_r(buf, " ", &end);
while (p) {
matrix[i / 9][i % 9] = strtol(p, NULL, 10);
i++;
p = strtok_r(NULL, " ", &end);
}
}
Is there any reason this doesn't work? Scan them in as integers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
int puzzle[9][9];
int i,j,count=0;
char value[81];
for( i = 0; i < 9; i++ ) {
for( j = 0; j < 9; j++ ) {
scanf("%d", &value[count]);
puzzle[i][j] = value[count];
printf("%d", puzzle[i][j]); //to verify it is stored correctly
count++;
}
}
}
EDIT: since you said it's coming from a file, i copy/pasted the sample file you gave into C:\file.txt, and the following code appears to work just dandy.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
FILE *fp;
int puzzle[9][9];
int i,j,count=0;
int value[81];
fp = fopen("C:\\file.txt", "r");
for( i = 0; i < 9; i++ ) {
for( j = 0; j < 9; j++ ) {
fscanf(fp, " %d", &value[count]);
puzzle[i][j] = value[count];
printf("element %d is %d\n",count, puzzle[i][j]);
count++;
}
}
}

Resources