C : convert to integer using bits - c

C : convert to integer using bits
I need to get integer value from bit arrays of 0, 1.
I want to pass integer arrays and get the decimal number using bit operator.
The following is what I tried but does not work when I tried to pass int arrays, it works with char* array. Is there any way that I can pass int arrays and convert it to decimal number? I want to use bit operator.
int toInt(int* bin_arr) {
int val = 0;
while (*bin_arr)
val = (val << 1) | (*bin_arr++ == '1');
return val;
}
Thanks in advance.

Your loop condition assumes that the array is 0-terminated, which is valid for strings, but not integer arrays. One way to fix this would be to pass a length parameter along with the int pointer, so you know when to stop iterating.
Also, in this expression:
(*bin_arr++ == '1')
you should remove the single quotes, if you're passing integers rather than characters.

Related

Why are my ASCII integer values becoming negative?

I am trying to do a very basic form of encryption and decryption by using operations on ASCII characters in C. I have the following code:
char* myEncrypt(char* stringToEncrypt)
{
char *encryptedString = malloc(256);
strcpy(encryptedString, stringToEncrypt);
int publicKey = 50;
for (int i = 0; encryptedString[i] && encryptedString[i] != '\n'; ++i)
encryptedString[i] = (encryptedString[i] + publicKey) % 256;
return encryptedString;
}
My issue is that when I run this code I am every so often getting negative values for my integer values of the ASCII characters assigned to encryptedString[i]. This is causing the decryption to fail. Looking at the code there should be no way for me to get negative values since I am using the modulo operation. Am I missing something simple here?
Many implementations use signed characters for plain chars. If you need the characters to be unsigned, then you'll need to use unsigned char.
For example, if you have a char value of 100, and you add 50, you get 150. If CHAR_MAX value is 127 (typical), then you end up with an implementation-defined value being assigned back to your character -- most likely wrapping around to -106.
Also, in C, a negative value will still be negative after a modulo operation. For example: -50 % 256 is -50. So if your original string had characters that were less than -50, you would end up with negative values after adding 50 and taking modulo 256 as well.

How to pass a variable value to an array in C

I am a novice programmer trying to understand arrays in C. Specifically I want to take the numeric value of a variable and feed it into an array. I tried to assign the value to the array, but failed with error messages. Can someone explain, simplistically, how to push a value into an array and then be able to just access the last digit?
My last attempt:
#include <stdio.h>
unsigned int TMR0 = 158;
int main(void)
{
unsigned int V = TMR0;
unsigned int Random[2] = {V};
printf("%d \n" , *(Random+2));
return 0;
Thanks.
unsigned int Random[2];
Array will be declared with two positions.
Random[0] Random[1] // two accessible positions in that array.
When you are assigning the value to the array,
unsigned int Random[2] = { V} ;
Value will be stored in the first position of array. Random[0].
*(Random+2) will access the position Random[2]. Which is not accessible position for this array. It will lead to undefined behaviour.
Another thing is if you need to assign the values to both the position you have to do like this.
unsigned int Random[2] = {V,V} ;
To access the last element in your array,
*(Random+1) or Random[1]
May this link will help.
You don't actually need an array to access digits of your number -- you just need math.
It's important to realise that "digit" implies a particular numeric base. In the computer, numbers are represented in binary. For convenience, they can be represented in our code using common bases: decimal, hexadecimal, and octal are the ones we generally use in languages like C.
So, to get the last digit in base 10, you would take the value modulo 10:
int val = 158;
int last_digit = val % 10;
printf( "%d\n", last_digit );
If you need to find digits other than the last, you can first perform integer division and then modulo:
int second_to_last_digit = (val / 10U) % 10;
Alternatively you can convert the number into a string, and then look at each character in that string. But I'm not going to go into that here, since it can be confusing to provide too much information to new programmers.

How to change a char to an integer?

I would like to copy the contents of a char array to int variables or an array. For example, the first five values have to go to an int array (int x):
char a[] = "123456";
I saw in other threads that to change a char to an int, I need to do this:
int x = a[0] - '0';
Is there other ways of doing it?
What if I wanted to the values in groups of two or more, such as 12, 34 and 56?
And what if I didn't what to save them as ints, but floats or other types instead?
Copy properly sized portions of the string to a separate buffer and use strtol() or strtod().
You are on write track, however if you want to convert into integer array then you
should use something like
int x[MAX_ELEM];
for(int i =0; i<sizeof(a)/sizeof(char); i++)
{
x[i] = a[i] -'0';
}
For other cases you will need to deal separately.
The reason you have to do int x = a[0] - '0'; is because of the character encoding in C. What is happening is you are subtracting the encoding offset from the character. Here is a table with all the encoding values: UTF-8 encodings. So int x = a[0] - '0'; is equivalent in your case to int x = 49 - 48; which has the correct value you were looking for. By using '0' instead of 0 you are using the char value of 0.
There are other ways of doing it, but this way works well. To use other types, just do type casting after you create the int.
John's way of getting two digit numbers works well. Reposted here, it was number = 10 * digit1 + digit2.
To answer your questions:
Sure, there are other ways of doing it. The way you've shown converts the ASCII value to the digit it represents, but there are other ways.
Read in the number of characters you want, convert each character to a digit, and construct the integer from those digits like number = 10 * digit1 + digit2.
Do type casting after you construct the integers.

C - Convert char to int to perform bitwise ops on output

I'm using a function (Borrowing code from: http://www.exploringbinary.com/converting-floating-point-numbers-to-binary-strings-in-c/) to convert a float into binary; stored in a char. I need to be able to perform bitwise operations on the result though, so I've been trying to find a way to take the string and convert it to an integer so that I can shift the bits around as needed. I've tried atoi() but that seems to return -1.
Thus far, I have:
char binStringRaw[FP2BIN_STRING_MAX];
float myfloat;
printf("Enter a floating point number: ");
scanf("%f", &myfloat);
int castedFloat = (*((int*)&myfloat));
fp2bin(castedFloat, binStringRaw);
Where the input is "12.125", the output of binStringRaw is "10000010100001000000000000000000". However, attempting to perform a bitwise operation on this give an error: "Invalid operands to binary expression ('char[1077]' and 'int')".
P.S. - I apologize if this is a simple question or if there are some general problems with my code. I'm very new to C programming coming from Python.
"castedFloat already is the binary representation of the float, as the cast-operation tells it to interpret the bits of myfloat as bits of an integer instead of a float. "
EDIT: Thanks to Eric Postpischil:
Eric Postpischil in Comments:
"the above is not guaranteed by the C standard. Dereferencing a
converted pointer is not fully specified by the standard. A proper way
to do this is to use a union: int x = (union { float f; int i; }) {
myfloat } .i;. (And one must still ensure that int and float are the
same size in the C implementation being used.)"
Bitwise operations are only defined for Integer-type values, such as char, int, long, ..., thats why it fails when using them on the string (char-array)
btw,
int atoi(char*)
returns the integer-value of a number written inside that string, eg.
atoi("12")
will return an integer with value 12
If you would want to convert the binary representation stored in a string, you have to set the integer bit by bit corresponding to the chars, a function to do this could look like that:
long intFromBinString(char* str){
long ret=0; //initialize returnvalue with zero
int i=0; //stores the current position in string
while(str[i] != 0){ //in c, strings are NULL-terminated, so end of string is 0
ret<<1; //another bit in string, so binary shift resutl-value
if(str[i] == '1') //if the new bit was 1, add that by binary or at the end
ret || 0x01;
i++; //increment position in string
}
return ret; //return result
}
The function fp2bin needs to get a double as parameter. if you call it with castedFloat, the (now interpreted as an integer)value will be implicitly casted to float, and then pass it on.
I assume you want to get a binary representation of the float, play some bitwise ops on it, and then pass it on.
In order to do that you have to cast it back to float, the reverse way you did before, so
int castedFloat = (*((int*)&myfloat));
{/*** some bitwise magic ***/}
float backcastedFloat = (*(float*)&castedFloat);
fp2bin(castedFloat, binStringRaw);
EDIT:(Thanks again, Eric):
union bothType { float f; int i; }) both;
both.f = myfloat;
{/*** some bitwise magic on both.i ***/}
fp2bin(both.f, binStringRaw);
should work

char array to integer array

I got a set of characters as input using scanf which is actually like this "1854?156X".
(using scanf("%c",&input[i]) , input is an array of 10 characters);
In further processing of code I want to multiply the (first digit *10) & (second digit *9) and so on.
So, while multiplying it is taking the ASCII value of 1 which is actually (49 *10), instead of (1*10).
input[i]*counter;
where counter is
int counter=10;
How can I convert the char array to integer array where the exact digit should be multiplied instead of ascii value of that character?
If you know ahead of time that you value is ascii then simply subtract the value of '0' from it. E.g. '9' - '0' = 9'
Definitely use atoi(). It spares you a lot of manual character checking.
int input_val = atoi(input);
int temp = input_val;
while(temp)
{
int digit = temp % 10;
temp /= 10;
}
This gives you each digit from right to left in "digit". You can construct your number using addition and multiplying by powers of 10.
Take the ascii value and subtract 48.
That is input[i] - '0'
...or rather use atoi(). It returns zero if it fails on conversion, so you don't need to bother with '?' and such characters in your array while you traverse it.
Use strtol to convert these character strings into integral types.
It's superior to atoi because the failure modes are not ambiguous.

Resources