Program to convert octal to binary number system - c

i am a beginner in c programing language and in this few days i'm train to do some c exercises
and i get stucked in some exercice for conversions:
so this is what i had did
#include <stdio.h>
#include <string.h>
int main() {
int num[8] = {
0,
1,
2,
3,
4,
5,
6,
7
};
long long binary, octal, tempoctal;
int last, i, A, tempi;
char hex[9] = {
'000',
'001',
'010',
'011',
'100',
'101',
'110',
'111'
};
int bex[10];
A = 0;
printf("enter an octal number: ");
scanf("%lld", & octal);
tempoctal = octal;
while (tempoctal != 0) {
last = tempoctal % 10;
for (i = 0; i < 8; i++) {
if (num[i] == last) {
tempi = i;
bex[A] = tempi;
}
}
A++;
tempoctal /= 10;
}
printf("\nthe is %s", bex);
return 0;
}
so i want just to know why when i want to print the array of bex
i get error on the consol enter image description here.
Although i know the solution but i want to do it in my own way.

Answering your question. bex is declared as int bex[10], array of integers. printf("%s"... expects a character string, not an array of int.
A character string is usually an array of chars char bex[10]. Char is a single byte, and an int is usually 4-byte long. So, you see the difference there. In your example you modify the lowest byte of the 'int', leaving other 3 as '0'.
printable chars have corresponding codes. For example a char of '0' has code of 48 in asccii encoding. All other chars that represent numbers have consecutive codes (48..57). This how the printf and other services know what to print if they see 48 in the byte.
the string in 'c' ends with a stray 0, so that the printf knows where to stop reading the chars.
So, if you want to print 'bex' as a string, you need to create it as a string. for example
char bex[10];
for (i=0; i <8; i++)
bex[A++] = '0' + i; // code of '0' + a number
bex[A] = 0; // string terminator
Just make sure that your 'A' is always less than '8' to avoid array overflow (string length of 9 plus one character for the terminator. Now you can do this.
printf("%s", bex);
You have to work on the rest of the program, because it does not do anything useful in the current state, but this should help you to get going.

Related

what's meant by converting an ASCII character to alphabetical index and how can i do that?

in Caesar (CS50) it says that i need to convert an ASCII character to alphabetical index in one of the steps. what does that mean? i saw a video that said that i "need to find the relationship between a number's ASCII value and its actual index in the alphabet", but i haven't really understood how I might implement this* and *what exactly is the relationship.
please elaborate in your answer because I'm new to this.
string plaintext = get_string("plaintext;");
As you may or may not know ASCII characters are encoded as 8-bit values and character constants, in reallity, have int type in C.
Using this knowledge you can perform character arithmetic as if they are regular numbers, take the following example:
printf("%d\n", 'a');
This prints 'a''s int value which is 97.
Now this:
printf("%d\n", 'g' - 'a');
This will print 6 which is the result of 103 - 97.
Now your string:
const char* plaintext = "plaintext";
for(size_t i = 0; i < strlen(plaintext); i++){
printf("%c - %d\n",plaintext[i], plaintext[i] - 'a' + 1);
}
The result:
p - 16
l - 12
a - 1
i - 9
n - 14
t - 20
e - 5
x - 24
t - 20
As you can see the printed results are the indexes of the letters in the alphabet 1...26, I added 1 to the result because, as you know, in C indexing starts at 0 and you would have 0...25.
So the bottom line is that you can use this character arithmetic to find the indexes of characters, this also aplies to caps, but you can't mix both.
Note that there are other character encodings that do not allow for this kind of arithmetic because the alphabetic characters are not in sequencial order, like, for example, EBCDIC.
It means that a single char variable is nothing but an integer containing an ASCII code, such as 65 for 'A'. It might be more convenient for an algorithm to work with the interval 0 to 25 than 65 to 90.
Generally, if you know that a char is an upper-case letter, you can do a naive conversion to alphabetical index by subtracting the letter 'A' from it. Naive, because strictly speaking the letters in the symbol (ASCII) table need not be located adjacently. For a beginner-level program, it should be ok though:
char str[] = "ABC";
for(int i=0; i<3; i++)
printf("%d ", str[i] - 'A'); // prints 0 1 2
Wheras a 100% portable converter function might look something like this:
int ascii_to_int (char ch)
{
const char LOOKUP_TABLE [128] =
{
['A'] = 0,
['B'] = 1,
...
};
return LOOKUP_TABLE[ch];
}
Here you have an example. It is portable as it does not depend if the char encoding.
const char *alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
int getIndex(const char *alphabet, int c)
{
int result = -1;
const char *res;
res = strchr(alphabet, c);
if(res)
{
result = res - alphabet;
}
return result;
}
int main(void)
{
char *str = "Hello World!!!";
while(*str)
{
printf("Index of %c is %d\n", *str, getIndex(alphabet, *str));
str++;
}
}
https://godbolt.org/z/rw2PK9

Print a Char Array of Integers in C

For class, I am required to create a function that converts an Integer into it's corresponding Binary number. However, I am forced to use the given main and parameters for the to_binary function. The whole problem requires me to print out the 32 bit binary number, but to break it up, I am just trying to print out the Char Array, that I thought I filled with Integers (perhaps the issue). When I do compile, I receive just a blank line (from the \n) and I am wondering how I can fix this. All I want to do is to be able to print the binary number for 5 ("101") yet I can't seem to do it with my professor's restrictions. Remember: I cannot change the arguments in to_binary or the main, only the body of to_binary. Any help would be greatly appreciated.
#include<stdio.h>
void to_binary(int x, char c[]) {
int j = 0;
while (x != 0) {
c[j] x = x % 2;
j++;
}
c[33] = '\0';
}
int main() {
int i = 5;
char b[33];
to_binary(i,b);
printf("%s\n", b);
}
This is the answer to your question.
void to_binary(int x, char c[]) {
int i =0;
int j;
while(x) {
/* The operation results binary in reverse order.
* so right-shift the entire array and add new value in left side*/
for(j = i; j > 0; j--) {
c[j] = c[j-1];
}
c[0] = (x%2) + '0';
x = x/2;
i++;
}
c[i]=0;
}
the problem is in the code below:
while (x != 0) {
c[j] = x % 2; // origin: c[j] x = x % 2; a typo?
j++;
}
the result of x % 2 is a integer, but you assigned it to a character c[j] —— integer 1 is not equal to character '1'.
If you want to convert a integer(0-9) to a character form, for example: integer 7 to character '7', you can do this:
int integer = 7;
char ch = '0' + integer;
One of the previous answers has already discussed the issue with c[j] x = x % 2; and the lack of proper character conversion. That being said, I'll instead be pointing out a different issue. Note that this isn't a specific solution to your problem, rather, consider it to be a recommendation.
Hard-coding the placement of the null-terminator is not a good idea. In fact, it can result in some undesired behavior. Imagine I create an automatic char array of length 5. In memory, it might look something like this:
Values = _ _ _ _ _
Index = 0 1 2 3 4
If I were to populate the first three indexes with '1', '0', and '1', the array might look like so:
Values = 1 0 1 _ _
Index = 0 1 2 3 4
Let's say I set index 4 to contain the null-terminator. The array now looks like so:
Values = 1 0 1 _ \0
Index = 0 1 2 3 4
Notice how index three is an open slot? This is bad. In C/C++ automatic arrays contain garbage values by default. Furthermore, strings are usually printed by iterating from character to character until a null-terminator is encountered.
If the array were to look like it does in the previous example, printing it would yield a weird result. It would print 1, 0, 1, followed by an odd garbage value.
The solution is to set the null-terminator directly after the string ends. In this case, you want your array to look like this:
Values = 1 0 1 \0 _
Index = 0 1 2 3 4
The value of index 4 is irrelevant, as the print function will terminate upon reading index 3.
Here's a code example for reference:
#include <stdio.h>
int main() {
const size_t length = 4;
char binary[length];
size_t i = 0;
while (i < length - 1) {
char c = getchar();
if (c == '0' || c == '1')
binary[i++] = c;
}
binary[i] = '\0';
puts(binary);
return 0;
}
#include<stdio.h>
int binary(int x)
{
int y,i,b,a[100];
if(x<16)
{
if(x%2==1)
a[3]=1;
if(x/2==1||x/2==3 || x/2==5 || x/2==7)
a[2]=1;
if(x>4 && x<8)
a[1]=1;
else if(x>12 && x<16)
a[1]=1;
if(x>=8)
a[0]=1;
}
for(i=0;i<4;i++)
printf("\t%d",a[i]);
printf("\n");
}
int main()
{
int c;
printf("Enter the decimal number (less than 16 ):\n");
scanf("%d",&c);
binary(c);
}
this code might help it will simply convert the decimal number less than 16 into the 4 digit binary number.if it contains any error than let me know

What does this C code snippet mean?

I've come across this piece of code here.
result = HMAC(EVP_md5(), key, 32, data, 28, NULL, NULL);
for (i = 0; i < result_len; i++) {
sprintf(&(res_hexstring[i * 2]), "%02x", result[i]);
}
what does the loop do? In particular what does &(res_hexstring[i * 2]) mean? Can't you just iterate through result as an array? Why is it an integer?
It converts the hash result to a string:
e.g., from:
char result[2] = {0xa1, 0xb2};
to
char res_hexstring[4 + 1] = {'a', '1', 'b', '2', '\0'}
The expression i * 2 appears in &res_hexstring[i * 2] because the byte 0xa1 needs two characters ('a' and '1') to be represented in a string.
The advantage of having a string is it can be then easily displayed:
printf("%s\n", res_hexstring); // display the hash result
for (i = 0; i < result_len; i++) {
sprintf(&(res_hexstring[i * 2]), "%02x", result[i]);
}
sprintf prints the result from the binary array result 1 byte <=> 2 nibbles / hexadecimal digits at a time into the buffer res_hexstring.
Which is the reason the left index goes 2 byte for each 1 byte the second is moved.
Of course, not using sprintf would be much faster, but it would also need a bit more code.
(Which might result in a bigger or smaller binary, but that must be measured if of interest.)
inline char to16digit(int x) { return x<10 ? '0'+x : 'A'-10+x; }
for (i = 0; i < result_len; i++) {
res_hexstring[i*2] = to16digit(result[i]>>4);
res_hexstring[i*2+1] = to16digit(result[i]&15);
}
res_hexstring[2*result_len] = 0;
There are various reasons you might want it in a human-readable form, serializing, printing and logging prominent among them. (And printf does not have a format to print such big numbers in hexadecimal notation.)

Array manipulation in C

I am like 3 weeks new at writing c code, so I am a newbie just trying some examples from a Harvard course video hosted online. I am trying to write some code that will encrypt a file based on the keyword.
The point is each letter of the alphabet will be assigned a numerical value from 0 to 25, so 'A' and 'a' will be 0, and likewise 'z' and 'Z' will be 25. If the keyword is 'abc' for example, I need to be able to convert it to its numerical form which is '012'. The approach I am trying to take (having learned nothing yet about many c functions) is to assign the alphabet list in an array. I think in the lecture he hinted at a multidimensional array but not sure how to implement that. The problem is, if the alphabet is stored as an array then the letters will be the actual values of the array and I'd need to know how to search an array based on the value, which I don't know how to do (so far I've just been returning values based on the index). I'd like some pseudo code help so I can figure this out. Thanks
In C, a char is an 8-bit integer, so, assuming your letters are in order, you can actually use the char value to get the index by using the first letter (a) as an offset:
char offset = 'a';
char value = 'b';
int index = value - offset; /* index = 1 */
This is hard to answer, not knowing what you've learned so far, but here's a hint to what I would do: the chars representing letters are bytes representing their ASCII values, and occur sequentially, from a to z and A to Z though they don't start at zero. You can cast them to ints and get the ascii values out.
Here's the pseudo code for how I'd write it:
Cast the character to a number
IF it's between the ascii values of A and Z, subtract it from A
ELSE Subtract it from the ASCII value of a or A
Output the result.
For what it's worth, I don't see an obvious solution to the problem that involves multidimensional arrays.
char '0' is the value 48
char 'A' is the value 65
char 'a' is the value 97
You said you want to learn how to search in the array:
char foo[26]; //your character array
...
...
//here is initialization of the array
for(int biz=0;biz<26;biz++)
{
foo[biz]=65+biz; // capital alphabet
}
...
...
//here is searching 1 by 1 iteration(low-yield)
char baz=67; //means we will find 'C'
for(int bar=0;bar<26;bar++)
{
if(foo[bar]==baz) {printf("we found C at the index: %i ",bar);break;}
}
//since this is a soted-array, you can use more-yield search algortihms.
Binary search algortihm(you may use on later chapters):
http://en.wikipedia.org/wiki/Binary_search_algorithm
The use of a multidimensional array is to store both the lower case and upper case alphabets in an array so that they can be mapped. An efficient way is using their ASCII code, but since you are a beginner, I guess this example will introduce you to handle for loops and multidimensional arrays, which I think is the plan of the instructor as well.
Let us first set up the array for the alphabets. We will have two rows with 26 alphabets in each row:
alphabetsEnglish[26][2] = {{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'},
{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}};
Now we can map elements of both cases.
int main()
{
int c,i,j;
char word[10];
printf("Enter a word:");
scanf("%s",word);
c=strlen(word);
printf("Your word has %d letters ", c);
for (i = 0; i < c; i++) //loop for the length of your word
{
for (j = 0; j <= 25; j++) //second loop to go through your alphabet list
{
if (word[i] == alphabetsEnglish[0][j] || word[i] == alphabetsEnglish[1][j]) //check for both cases of your alphabet
{
printf("Your alphabet %c translates to %d: ", word[i], j);
}
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *conv(char* str){
static const char* table = "abcdefghijklmnopqrstuvwxyz";
int size, *ret, *p;
if(NULL==str || *str == '\0') return NULL;
size = strlen(str);
ret=p=(int*)malloc(size*sizeof(int));
while(*str){
char *pos;
pos=strchr(table, tolower(*str++));
*p++ = pos == NULL ? -1 : pos - table;
}
return ret;
}
int main(void){
char *word = "abc";
int i, size = strlen(word), *result;
result = conv(word);
for(i=0;i<size;++i){
printf("%d ", result[i]);//0 1 2
}
free(result);
return 0;
}

Parsing Integer to String C

How does one parse an integer to string(char* || char[]) in C? Is there an equivalent to the Integer.parseInt(String) method from Java in C?
If you want to convert an integer to string, try the function snprintf().
If you want to convert a string to an integer, try the function sscanf() or atoi() or atol().
To convert an int to a string:
int x = -5;
char buffer[50];
sprintf( buffer, "%d", x );
You can also do it for doubles:
double d = 3.1415;
sprintf( buffer, "%f", d );
To convert a string to an int:
int x = atoi("-43");
See http://www.acm.uiuc.edu/webmonkeys/book/c_guide/ for the documentation of these functions.
It sounds like you have a string and want to convert it to an integer, judging by the mention of parseInt, though it's not quite clear from the question...
To do this, use strtol. This function is marginally more complicated than atoi, but in return it provides a clearer indication of error conditions, because it can fill in a pointer (that the caller provides) with the address of the first character that got it confused. The caller can then examine the offending character and decide whether the string was valid or not. atoi, by contrast, just returns 0 if it got lost, which isn't always helpful -- though if you're happy with this behaviour then you might as well use it.
An example use of strtol follows. The check for error is very simple: if the first unrecognised character wasn't the '\x0' that ends the string, then the string is considered not to contain a valid int.
int ParseInt(const char *s,int *i)
{
char *ep;
long l;
l=strtol(s,&ep,0);
if(*ep!=0)
return 0;
*i=(int)l;
return 1;
}
This function fills in *i with the integer and returns 1, if the string contained a valid integer. Otherwise, it returns 0.
This is discussed in Steve Summit's C FAQs.
The Java parseInt() function parses a string to return an integer. An equivalent C function is atoi(). However, this doesn't seem to match the first part of your question. Do you want to convert from an integer to a string, or from a string to an integer?
You can also check out the atoi() function (ascii to integer) and it's relatives, atol and atoll, etc.
Also, there are functions that do the reverse as well, namely itoa() and co.
You may want to take a look at the compliant solution on this site.
You can try:
int intval;
String stringval;
//assign a value to intval here.
stringval = String(intval);
that should do the trick.
This is not an optimal solution. This is my solution given multiple restrictions, so if you had limited resources based on your course/instructor's guidelines, this may be a good fit for you.
Also note that this is a fraction of my own project implement, and I had to read in operands as well as digits, so I used getchars. Otherwise, if you only need integers and no other type of characters, I like using this:
int k;
while (scanf("%d", &k) == 1)
The rules were no specific, "advanced" C concepts: no String variables, no structs, no pointers, no methods not covered, and the only include we were allowed was #include
So with no simple method calls like atoi() available or any String variables to use, I chose to just brute force it.
1: read chars in using getchar (fgets was banned). return 1 (exit status 1) if
there is an invalid character. For your problem based of parseInt in Java
1 11 13 is valid but 1 11 1a is invalid, so for all values we have a valid "string" iff all chars are 0-9 ignoring whitespace.
2: convert the ASCII value of a char to its integer value (eg. 48 => 0)
3: use a variable val to store an int such that for each char in a "substring" there is a corresponding integer digit. i.e. "1234" => 1234 append this to an int array and set val to 0 for reuse.
The following code demonstrates this algorithm:
int main() {
int i, c;
int size = 0;
int arr[10]; //max number of ints yours may differ
int val = 0;
int chars[1200]; //arbitrary size to fit largest "String"
int len = 0;
//Part 1: read in valid integer chars from stdin
while((c = getchar()) != EOF && (c < 58 && c > 47)) {
chars[len] = c;
len++;
}
//Part 2: Convert atoi manually. concat digits of multi digit integers and
// append to an int[]
for(i = 0; i < len; i++){
for(i = 0; i < len; i++){
if(chars[i] > 47 && chars[i] < 58){
while((chars[i] > 47 && chars[i] < 58)){
if(chars[i] == 48)
c = 0;
if(chars[i] == 49)
c = 1;
if(chars[i] == 50)
c = 2;
if(chars[i] == 51)
c = 3;
if(chars[i] == 52)
c = 4;
if(chars[i] == 53)
c = 5;
if(chars[i] == 54)
c = 6;
if(chars[i] == 55)
c = 7;
if(chars[i] ==56)
c = 8;
if(chars[i] == 57)
c = 9;
val = val*10 + c;
i++;
}
arr[size] = val;
size++;
if(size > 10) //we have a check to ensure size stays in bounds
return 1;
val = 0;
}
//Print: We'll make it a clean, organized "toString" representation
printf("[");
for(i = 0; i < size-1; i++){
printf("%d, ", arr[i]);
}
printf("%d]", arr[i];
return 0;
Again, this is the brute force method, but in cases like mine where you can't use the method concepts people use professionally or various C99 implements, this may be what you are looking for.

Resources