Converting a char to an int for int arithmetic in java - arrays

i have a bit of strange confusion happening when trying to convert my char variables from my char array into ints.
Here is my code:
public class Luhn {
private String cardNumber;
private char[] cardArray;
public Luhn(String cardNumber) {
this.cardNumber = cardNumber;
cardArray = new char[cardNumber.length()];
for (int i = 0; i < cardNumber.length(); i++) {
cardArray[i] = cardNumber.charAt(i);
}
public void calculation() {
for(int i = cardArray.length-1; i >= 0; i-=2) {
char y = cardArray[i];
int x = (int) (cardArray[i] * 1);
if(x > 9) {
//int total = 0;
}
}
}
I keep getting strange outputs in x. Something like 58. I'm accessing the array backwards and retrieving every 2nd number back to the front of the array. I basically want x to be whatever the number is in each array element. I know with this small piece of code it will overwrite x continuously, but i want it to be the number designated in the char array, not some random number not matching my array elements. The problem is in the calculation method where i try and convert the char to int.
Please help
Thanks.
For Example;

You can do
(int)(cardArray[i] - '0')
to convert a single digit to a number.
The reason you can do this is because each char is a number.
'0' = 48
'1' = 49
'2' = 50
'3' = 51
...
'9' = 57
Subtraction the value for 0 gets you the integer value for each of the characters.

chars are actually numbers that represent chars. if you want to convert it into an int, subtract the 0 char
int x = (int) (cardArray[i] - '0');

You could use Character.getNumericValue(char), See JavaDoc here

Related

Program to convert octal to binary number system

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.

How do I add a 2 Digit number inside an Array as a single entry using getch()?

I've got this example which I made but it doesn't work.
This code is supposed to add XX:YY:ZZ to an array that has 3 columns: realtime = {XX, YY, ZZ}
#include <stdio.h>
#include <conio.h>
int main() {
int realtime[3];
char time[8];
for(int i = 0;i<8;i++){
time[i] = getche();
}
for(int i = 0, j = 0;i<3;i++, j+=3){
realtime[i] = (time[j])*10+time[j+1];
}
}
Notice that the character '0' does not have the integer value 0. See for instance https://en.wikipedia.org/wiki/ASCII
The integer value of the character '0' is normally 48. So if you read the text string "01:23:45", you'll end up with time[0] having the integer value 48, time[1] having the integer value 49, time[3] having the integer value 50 and so on.
Therefore you need to subtract 48 to the values in time in the second loop. That is normally done by: time[j]-'0'.
Try this:
for(int i = 0, j = 0;i<3;i++, j+=3){
realtime[i] = ((time[j]-'0')*10+(time[j+1]-'0');
// ^^^^ ^^^^^
}

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

extracting a char from a char.Eg 1 from 123

In this program convert.c, I am trying to convert a given number of any base to base 10. The command is given as convert .todecimal is supposed to do that. The code below has errors of course but I am not sure how to make it work. For eg,the number in argv[3]is 123 in base 9. The equation is supposed to work like this :(1 x 9^2) + (2 x 9^1) + (3 x 9^0) = (102)10.where the variables are (n x argv[3]^i) + (n+1 * argv[3]^i-1)....How do i get a char of 123 when 123 itself a char? Any help is appreciated.
#include<stdio.h>
#include<math.h>
int todecimal();
main(int argc, char *argv[])
{
int s = 0;
int i = 0;
int n = 1;
if (argc < 4) {
printf("Usage: convert <basefrom> <baseto> <number>\n");
}
printf("to decimal prints %d" todecimal());
}
int todecimal() {
if (argv[3] > 0) {
if ((getchar(argv[3]) != NULL)) {
i = i + 1;
}
while (i >= 0) {
s = s + (n * (pow(argv[3],i)));
n = n + 1;
i = i - 1;
}
return s;
}
}
There is a difference between char and char*. The latter is a pointer to char, also used as a string (a sequence of chars). So, wherever you can have more than one char, you use a pointer (to the first one) instead - this is your argv[3].
So, to get one char from a sequence of chars, you apply square brackets:
argv[3] - is the whole string, let's pretend it's "192" to reduce confusion
argv[3][0] - is the first char, '1'
argv[3][1] - is the second char, '9'
argv[3][2] - is the third char, '2'
In your case, you need argv[3][i]. But you have to fix your other bugs too (there are many, as other people noted).

Accessing elements in a string?

I have to convert a given binary input (e.g. 1101) to decimal, but the input isn't a string array or an integer (the passed argument is const char *binstr). How am I supposed to access each individual digit of the binary number so I can do pow(x,y) on each and add them together to get the decimal number?
const char * usually refers to a C string. You can just use strtol(3):
int x = strtol(binstr, NULL, 2);
You could try with this program which converts from Binary to Decimal
char *binstr = "1011011";
int num = 0, sum = 0, ctr = 0;
ctr = strlen(binstr) - 1;
do{
sum += ((binstr[ctr] & 0x1) << num);
ctr--;
num ++;
}while(ctr >= 0);
binstr[0];
binstr[1];
binstr[2];
etc
or you can do it through a pointer
char* s = binstr;
unsigned long x =0;
while(*s) { x = x << 1; x |= (*s == '1' ? 1:0); s++;}
printf("the decimal of %s is %ul", binstr, x);
You've made a c string and you can get each character the way similar to arrays:
input[i]
Here's an example of splitting the binary string into individual bits (characters) and printing them out: http://cfiddle.net/wYtKJv
You can use loops:
while(i<100){
if(binstr[i]== '\0'){
break;
}
printf("First Bit:\n%c\n\n",binstr[i]);
i++;
}
Since C-strings are null terminated you can check to see if a character if we hit is '\0' to break the loop.
In the loop you can also convert the chars to ints and store them someplace (array probably) where you can access them for calculations.

Resources