Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
If I have the number 88 how would I add 00 to the end of and turn it into 8800? Bitwise shifts is the only way I can think of to do this but it doesn't work. It completely changes the numbers.
Bitwise shifts can only be used to multiply by powers of two, you simply want multiplication. Just run:
printf("%d", 88 * 100);
to print 8800.
If all you want to do is literally add 00 to the end of numbers you can instead do:
printf("%d00", 88);
You cannot do everything with bitwise shift operators alone. Its mathematically impossible to say it straight. But if you still insist you can do something like (88 << 6) + (88 << 5) + (88 << 2)
As a comment points out your answer can be obtained simply by multiplying your number by hundred.
So, you read from a file, and want to add two zeroes to it. Two ways I can see to do this: String-wise and Numerically.
String-wise, you can use
strcat(inputedText, "00");
(or just printf, or possible other solutions)
numerically, you can convert the inputted data from the file to an int, and multiply it by 100. If you need to print it, Vality's answer shows how to do that.
Live run: http://ideone.com/wiW5Zb
#include <stdio.h>
#include <stdint.h>
int64_t calc(int64_t value)
{
int64_t t = 1;
while(t < value)
t *= 10;
return t;
}
int64_t concatnum(int64_t a, int64_t b)
{
return (a * calc(b)) + b;
}
int main()
{
int a = 1000;
int b = 11;
int c = concatnum(a, b); //b must be greater 10.
printf("%d", c);
return 0;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to write a C program to convert a number given a base, to any other base (Eg. base 2 binary number to base 8, or base 3 to base 16 hex). I've researched this quite a bit, and already read through a similar article, The math behind converting from any base to any base without going through base 10?] but in the explanation given, they utilize an array, which I am not allowed to do for this program.
Without writing a lengthy program with a method for each possible combination of base conversion, I don't see how this is possible without an array to store possible values. I do understand that there is a change of base formula with logs that allows me to change between number bases, but I am unclear how I would apply this, as this formula only gives a decimal number answer, which I would still need to convert.
int log_base_n(int n, int logof)
{
double logBaseN = log10((double) logof) / log10((double) n);
return (int) ceil(logBaseN);
}
Here is my binary to decimal conversion which I am trying to use as an intermediate step:
/**
* Convert decimal numbers to binary. Uses a greedy subtraction
* algorithm. Assumes max integer allowed is 2 to 16 power.
*
* #param numberToConvert
*/
void decToBin(int numberToConvert)
{
int power = 16;
double ans = pow(2, power);
if (numberToConvert > ans)
{
printf("ERROR: Number too large to convert!\n");
return;
}
while (ans > numberToConvert)
{
power--;
ans = pow(2, power);
}
printf("%d", 0);
int i = power;
while (i >= 0)
{
ans = pow(2, i);
numberToConvert = numberToConvert - ans;
printf("%d", 1);
i--;
while ((pow(2, i) > numberToConvert) && (i >= 0))
{
printf("%d", 0);
i--;
ans = pow(2, i);
}
}
}
I know Java has a parseInt() method, that does base conversions, but is there something similar I can implement in C without having to write methods for each possible conversion like the one above, while still utilizing a logarithm related idea? Any help would be greatly appreciated.
but is there something similar I can implement in C without having to write methods for each possible conversion like the one above, while still utilizing a logarithm related idea?
Logarithm is a poor choice. The computation of logs in code is not exactly the same as their mathematical counterpart and leads to incorrect output.
The below is a problem should the quotient result in a value just a little higher than a whole number expected value. Of course, log10() is a problem for logof <= 0.
double logBaseN = log10((double) logof) / log10((double) n);
return (int) ceil(logBaseN);
Further, the calculation of log_base_n() is quite unnecessary.
This is an integer problem. Use integer math.
A simply non-array solution "to convert from any base to another base"1 is to use recursion.
void print_int_base(int numberToConvert, int base) {
// For now, assume numberToConvert >= 0, 2 <= base <= 36
if (numberToConvert >= base) {
print_int_base(numberToConvert/base, base);
}
int digit = numberToConvert%base;
int c = digit < 10 ? digit + '0' : digit + 'A';
putchar(c);
}
Test code
#include <stdio.h>
void print_int_base_test(int numberToConvert, int base) {
printf("%10d %2d:", numberToConvert, base);
print_int_base(numberToConvert, base);
puts("");
}
int main() {
int numberToConvert = 42;
for (int base=2; base<=20; base++) {
print_int_base_test(numberToConvert, base);
}
}
Output
42 2:101010
42 3:1120
42 4:222
42 5:132
42 6:110
42 7:60
42 8:52
42 9:46
42 10:42
42 11:39
42 12:36
42 13:33
42 14:30
42 15:2M
42 16:2K
42 17:28
42 18:26
42 19:24
42 20:22
1 OP's idea of conversion apparently is to print the int in various bases.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have two functions which supposedly can convert decimals to binary, however I can't seem to get them to work if the decimal is above 3 (I get weird negative numbers). I can't fully understand the code in the functions as I've only just started to learn C, however I was hoping if someone could tell me if the functions work, or if I am just not doing something right i.e. should I be using int32_t type as the value to pass into the function?
uint8_t dec_to_bin(int decimal){
int n = decimal, i, j, binno=0,dn;
dn=n;
i=1;
for(j=n;j>0;j=j/2)
{
binno=binno+(n%2)*i;
i=i*10;
n=n/2;
}
return binno;
}
uint8_t dec_to_bin2(int decimal){
long long binaryNumber = 0;
int remainder, i = 1;
while (decimal!=0){
remainder = decimal%2;
decimal /= 2;
binaryNumber += remainder*i;
i *= 10;
}
return binaryNumber;
}
Unfortunately I have no way to find out the values of the binary numbers as a uint_8 type as I am doing this on a micro-controller and there is no way to debug or print values anywhere (I have posted numerous threads asking how to do this, with no luck). We have however been provided with another function:
int bin_to_dec(uint64_t binary) {
int result = 0;
for ( int i = 7; i >= 0; i-- ) {
result = result * 10 + ((binary >> i) & 1);
}
return result;
}
This function converts the binary number back to an integer so I can display it on the screen with a library function (the library function can only display integers or strings). If I pass 10 into either of the decimal to binary converter functions, then pass the uint_8 value from either function to the binary to decimal converter and print to the LCD, I get -3110. This should just be 1010.
I'm sorry to say, but your dec_to_bin and dec_to_bin2 functions are meaningless. Throw them away. They might -- might -- have a tiny bit of value as a teaching exercise. But if you're trying to write actual code for a microcontroller to actually do something, you don't need these functions, and you don't want these functions. (Also you need to understand why you don't need these functions.)
The problem is not that they're implemented wrongly. They're fundamentally flawed in their very intent.
These functions seem to convert, for example, the integer 5 to the integer 101, and at first glance that might look like "decimal to binary conversion", but it's not. You've just converted the number five to the number one hundred and one.
Let's look at this a different way. If I say
int i = 17;
and if I then call
printf("%d\n", i);
I see the value "17" printed, as I expect. But I can also call
printf("%x\n", i);
and this prints i's value in hexadecimal, so I see "11". Did I just convert i from decimal to hexadecimal? No, I did not! I took the same number, "seventeen", and I printed it out in two different ways: in decimal, and in hexadecimal.
For all practical purposes, unless you're designing the actual hardware a program will run on, it really doesn't make sense to ask what base a number is stored in. A variable like int i is just a number, an integer. (Deep down inside, of course, on a conventional processor we know it's stored in binary all the time.)
The only time it makes sense to explicitly convert a number to binary is if you want to print it out in a human-readable text representation, in binary. In that case, you're converting from an integer to a string. (The string will consist of the characters '0' and '1'.)
So if you want to write a meaningful decimal-to-binary converter (which will actually be an anything-to-binary converter), either have it print the binary number out to the screen, or store it in a string (an array of characters, or char []).
And if you're in a class where you're being asked to write uint8_t dec_to_bin(int decimal) (or where your instructor is giving you examples of such functions), I can't help you, and I'm afraid you're doomed. Half of what this instructor is teaching you is wrong or badly misleading, will seriously handicap you from ever being a successful C programmer. Of course I can't tell you which half, because I don't know what other lies you're being taught. Good luck -- you'll need it! -- unlearning these false facts later.
I don't know why you're trying to store binary data as base 10 numbers instead of just printing or storing (as a char[]) the bits of an int (get kth bit of n as (n >> k) & 1 then print/store), but I'll assume it's necessary.
Your solution could be prone to overflowing the uint8_t as mentioned in the comments. Even a uint64_t can only hold 19 bits of binary data in the format you're using, less than the 32 of typical ints. The return type of your second function is still uint8_t, this might just be a typo, but it means the internal representation of long long will be implicitly cast on return.
I've written some functions based on yours, but with a little more bit manipulation that work for me.
uint64_t dec_to_bin (int n)
{
uint64_t result = 0;
int k, i;
// 64 bits can only hold 19 (log10(2^64)) bits in this format
for (i = 0, k = n; k && i < 19; i++) {
// Because the loop is limited to 19 we shouldn't need to worry about overflowing
result *= 10;
result += (n >> i) & 1;
k /= 2;
}
return result;
}
int bin_to_dec (uint64_t n)
{
int result = 0;
while (n) {
result <<= 1;
result += n % 2;
n /= 10;
}
return result;
}
I tested your functions on the input 43 on my system and got
43 // Original Input
101011 // dec_to_bin2 with long long return type
10010011 // bin_to_dec
With an appropriately sized output, your dec_to_bin2 function does work as expected.
And my functions:
43 // Original Input
110101 // dec_to_bin
43 // bin_to_dec
The endianness may not be what you're expecting, but that can be changed if necessary.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to perform the following operation:
double exponent = pow(2.0, -254)
The result I get is 'inf', the actual result is: 3.4544e-77, which is a very small number, I would guess that I could get '0' instead but I get 'inf'.
I need the actual result, is there a way to improve precision on a double? I have tried also long double without success.
I'm programming on C with Visual Studio.
In C, you can multiply by powers of two with scalb, so scalb(1, -254) is 2−254. You can also use powers of two in hexadecimal floating-point constants; 2−254 is 0x1p-254.
However, pow(2.0, -254) does not return infinity. If you attempted to print the return value, and “inf” was printed, there is an error in your source code.
Yes, the problem was in my source code, my original code is:
#include <math.h>
void main()
{
unsigned int scale = 1;
unsigned int bias = 255;
double temp = pow(2.0, scale - bias);
printf("Number is: %e\n", temp);
return;
}
which Im guessing the operation 'scale-bias' is overflowing since they are UINTS, thus getting me a 'inf', changing them to INT solves the issue:
#include <math.h>
void main()
{
int scale = 1;
int bias = 255;
double temp = pow(2.0, scale - bias);
printf("Number is: %e\n", temp);
return;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
say i have:
55.3 and want 55
55.6 and want 56
81.1 and want 81
etc.
i have been trying to use the round() function but it seems to keep giving me the highest value for all decimal places.
OP has not posted code that failed. Certain OP coded incorrectly.
Using round() is the correct way to round a double before converting to an int. Of course it must be in range.
#include <math.h>
#include <assert.h>
int round_to_int(double x) {
x = round(x);
assert(x >= INT_MIN);
assert(x < (INT_MAX/2 + 1)*2.0);
return (int) x;
}
See How to test for lossless double / integer conversion? for details about the assert()s.
Why not use (int)(x + 0.5);?
1) It fails for negative numbers.
2) It can fail for the double just smaller than 0.5 as the x + 0.5 can round to 1.0.
3) When the precision of int exceeds double, values where the least significant bit is 0.5 or 1.0, x+0.5 may round to the next integer.
4) Unadorned, it has no range checking.
In the olden days we used to say int the_int = (int)(some_double + 0.5); (obviously beware if you are dealing with negative values too).
Increase the magnitude by one half and truncate:
int round_up_or_down(double x)
{
return x > 0 ? x + 0.5 : x - 0.5;
}
This distributes the real intervals uniformly:
...
[-1.5, -0.5) => -1
[-0.5, +0.5) => 0
[+0.5, +1.5) -> +1
...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I integrate an equation including bessel functions numerically from "0" to "infinity" in Fortran or/and C?
I did in matlab, but it's not true for larger inputs and after a specific values , the bessel functions give completely wrong results(there is a restriction in Matlab)
There's a large number of analytic results for various integrals of the Bessel functions (see DLMF, Sect. 10.22), including definite integrals over precisely this range. You'd be much better off, and almost certainly faster and more accurate, trying hard to recast your expression into something that's integrable and using an exact result.
Last time I had to do with such things, it was state of the art to do simple integration of the intervals defined by the zero crossings. That is in most cases relatively stable and if the integrand is approaching zero reasonable fast easy to do.
As a starting point for playing around I´ve included a bit of code. Of course you need to work on the convergence detection and error checking. This is no production code but I thought maybe it provides a starting point for you. Its using gsl.
On my iMac this code takes about 2 µs per iteration. It will not become faster by including a hardcoded table for the intervals.
I hope this is of some use for you.
#include <iostream>
#include <vector>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sf.h>
double f (double x, void * params) {
double y = 1.0 / (1.0 + x) * gsl_sf_bessel_J0 (x);
return y;
}
int main(int argc, const char * argv[]) {
double sum = 0;
double delta = 0.00001;
int max_steps = 1000;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (max_steps);
gsl_function F;
F.function = &f;
F.params = 0;
double result, error;
double a,b;
for(int n=0; n < max_steps; n++)
{
if(n==0)
{
a = 0.0;
b = gsl_sf_bessel_zero_J0(1);
}
else
{
a = n;
b = gsl_sf_bessel_zero_J0(n+1);
}
gsl_integration_qag (&F, // function
besselj0_intervals[n], // from
besselj0_intervals[n+1], // to
0, // eps absolute
1e-4,// eps relative
max_steps,
GSL_INTEG_GAUSS15,
w,
&result,
&error);
sum += result;
std::cout << n << " " << result << " " << sum << "\n";
if(abs(result) < delta)
break;
}
return 0;
}
You can pretty much google and find lots of Bessel functions implemented in C already.
http://www.atnf.csiro.au/computing/software/gipsy/sub/bessel.c
http://jean-pierre.moreau.pagesperso-orange.fr/c_bessel.html
https://msdn.microsoft.com/en-us/library/h7zkk1bz.aspx
In the end, these use the built in types and will be limited to the ranges they can represent (just as MATLAB is). At best, expect 15 digits of precision using double precision floating point representation. So, for large numbers, they will appear to be rounded. eg. 1237846464123450000000000.00000
And, of course, others on Stack Overflow have looked into it.
C++ Bessel function for complex numbers