I have an integer say 002345 I want it to be split into Hours=00 Mins=23 Sec=45.I tried using "/" and "%" formula methods but it didn't work out since the first two terms are 00 is there any other way.can any one of you present me with a code.
thank you
Since you are not asking for conventional method of using "/" and "%".
Then you could convert the integer time to string and strip out hour, min, sec.
But storing time as simple integer is NOT a good idea, you would miss the leading zeros for hours. Hence its better to use a char array for this.
#include <stdio.h>
#include <string.h>
int main()
{
char hour[3]={0};
char min[3]={0};
char sec[3]={0};
int time = 2345;
char timeStr[10] = {0};
sprintf(timeStr, "%06d", time);
memcpy(hour, timeStr, 2);
memcpy(min, timeStr+2,2);
memcpy(sec, timeStr+4,2);
printf("%s:%s:%s",hour,min,sec);
}
Way i recommend is:-
#include <stdio.h>
#include <string.h>
int main()
{
char hour[3]={0};
char min[3]={0};
char sec[3]={0};
char timeStr[] = "002345";
memcpy(hour, timeStr, 2);
memcpy(min, timeStr+2,2);
memcpy(sec, timeStr+4,2);
printf("%s:%s:%s",hour,min,sec);
}
Then convert hour,min, sec to integer using atoi();
Assuming your integer is 2345 (since leading zeroes are irrelevant), you can just use:
hh = val / 10000;
mm = (val / 100) % 100;
ss = val % 100;
If instead you have a string (it's unclear because your tags indicate this but there's no mention of it in the question body), you simply call something like atoi or strtol on each two-character segment.
Related
I'm developing an ARM embedded application. I'm kind of stuck on a silly problem - I have an array of unsigned 8-bit integers:
uint8_t days[42] = { 0 };
It's initialized with some data - the initialization algorithm introduces a lot of variables confusing and irrelevant to the problem, so I will not repost it here. I see this array in the debugger variable watch, and I'm certain it is filled with integer values from 0 to 31.
I'd like to take any element of this array, say 15th, and convert it to char* so that it can be displayed on my LCD screen. I rewrite it using sprintf function:
char d[3] = { '0', '0', '0' };
sprintf(d, "%d", days[15]);
Just one note: no, I can't use the stdlib itoa() function, because it does not conform to MISRA-C standards, which I am obliged to follow.
As a result, I only get a binary zero value in my d buffer. Any ideas?
For MISRA-C compliance, you can certainly not use sprintf() or anything else from stdio.h either. You generally want to avoid sprintf like the plague on any embedded system anyhow.
Writing a simple decimal integer to string conversion routine is quite basic stuff... here's my attempt of a MISRA-C (2004 and 2012) compatible version:
#include <stdint.h>
void dec_to_str (char* str, uint32_t val, size_t digits);
int main (void)
{
char str[3u + 1u]; // assuming you want null terminated strings?
dec_to_str(str, 31u, 3u);
return 0;
}
void dec_to_str (char* str, uint32_t val, size_t digits)
{
size_t i=1u;
for(; i<=digits; i++)
{
str[digits-i] = (char)((val % 10u) + '0');
val/=10u;
}
str[i-1u] = '\0'; // assuming you want null terminated strings?
}
Note: the uint32_t variable could get swapped out for an uint8_t, but then you need to add type casts all over the place, to prevent implicit type promotions, as required by MISRA. The code will then turn really ugly, like this:
str[digits-i] = (char)(uint8_t)((uint8_t)(val % 10u) + '0');
The only sane thing to do then, is to split that mess into several lines:
uint8_t ch = (uint8_t)(val % 10u);
ch = (uint8_t)(ch + '0');
str[digits-i] = (char)ch;
#include "stdafx.h"
#include <stdio.h>
int days[2] = {12,14};
char d[3] = {'0', '0', 0};
int _tmain(int argc, _TCHAR* argv[])
{
d[0] = days[1] / 10 + 0x30; // convert 10's digit to ascii
d[1] = days[1] % 10 + 0x30; // convert 1's digit to ascii
// Debugging help
printf(d);
getchar();
return 0;
}
So I'm trying to copy part of an array into another array in the simplest way possible. I was trying to avoid using a loop. This was my thought process...
char date[]="20140805";
char year =date[0..3];
The ".." is what is causing the error. I want to be able to break up the date variable into parts, and was hoping to be able to do so compactly in one line like this. Some help would be appreciated.
You should not use a loop.
char year[5];
char date[] = "20140805";
memcpy(year, date, 4);
year[4] = 0;
that's how you should do it, or may be you want
char date[] = "20140805";
char year[] = {date[0], date[1], date[2], date[3], 0};
Here is an example to do that :
In fact you can copy any part of a string using this method :)
just change the from and sz variable and you are done :)
#include <stdio.h>
#include <string.h>
int main ()
{
char date[]= "20140805";
int sz=4; // number of characters to copy
char year[sz+1];
int from = 0; // here from is where you start to copy
strncpy ( year, date + from, sz );
year[sz]=0;
puts (year);
return 0;
}
OP wanted a one-liner: here in one declaration plus one line.
char year[5] = {0};
strncpy(year,date,4);
This answer addresses the weak point of strncpy() which does not append a final 0 if count <= strlen(source);. It's not the best solution but it answers OP's question while avoiding the trap.
Byte dumps of the char array before and after the strncpy()
0 0 0 0 0
50 48 49 52 0
hi i am making a programming language that will run on the nintendo gameboy in c
which is why you will see some functions like waitpad();
but this question is unrelated the the gameboy librarys
for some reason when ever i try to increment a certain variable in my main.c file:
#include <stdio.h>
#include <gb/gb.h>
#include "convert.h"
#include "display.h"
#include "input.h"
#include "functions.h"
#include "interpreter.h"
unsigned char cnt[5] = {1,2,3,4,5};//cnt is short for counters
unsigned char k = 0;
unsigned char running = 1;
unsigned char memory[2048];
unsigned char code[2048];
int main()
{
Clear_mem();
Clear_code();
while(running == 1) {
display(cnt[0],cnt[1],cnt[2],cnt[3],cnt[4]);
printf("cnt[0] = %d\n", cnt[0]);
cnt[0]++;//turns into -17918
printf("Press Start To Enter Next Character\n");
waitpad(J_START);
code[k] = input();
interpret(code[k]);
k++;
}
return 0;
}
cnt[0] turns into -17918
can anyone see any problem that would cause it to behave this way?
You ask if anyone sees a problem, well - yes, here is a problem:
unsigned char k = 0;
unsigned char running = 1;
unsigned char code[2048];
while(running == 1) {
code[k] = input();
k++;
}
If k >= 2048, then code[k] = ... will cause a memory-override.
After a memory-override, pretty much anything can happens (undefined behavior).
Having said that, the value of k can be larger than 2047 only if CHAR_BIT is larger than 11.
Add #include <limits.h> to your program and make sure that CHAR_BIT is not larger than 11.
You have to convert it to an integer, because that's what you're trying to print:
printf("cnt[0] = %d\n", (int) cnt[0]);
When you're using a variadic function like printf, you have to make sure you're passing the right type. Check your compiler warning settings, new compilers can easily detect these kind of problems.
if you want to print the character value of your character variable you should print it like this:
printf("cnt[0] = %c\n", cnt[0]);
If you print it using %d the expansion of the character to a size of int could be negative for characters over half a character's size (0x80 and up).
If you insist on printing it as an int cast the variable like this:
printf("cnt[0] = %d\n", (int)cnt[0]);
eg: 1589745896214758962147852.
This is a question I have been slogging out for a while now.
What are the possible ways?
What is the best practice?
You could just call the random number generator 25 times for each digit - simple if you want this as a string.
If you don't have a random number function available there is a simple to implement one.
http://xkcd.com/221/
This is a nice question...
You can use OpennSsl BIGNUM.
This is a simple fatorial example.
#include <stdio.h>
#include <openssl/bn.h>
int main(int argc, char **argv)
{
BIGNUM *fat;
BN_ULONG a, f;
char *resp;
int i;
fat = BN_new();
for (i = 1; i < argc; i++) {
f = atoll(argv[i]);
BN_dec2bn(&fat, "1");
for (a = 2; a <= f; a++) {
BN_mul_word(fat, a);
}
resp = BN_bn2dec(fat);
printf("Fatorial of %s = %s\n", argv[i], resp);
}
return 0;
}
I just dicovered a better example:
#include <stdio.h>
#include <openssl/bn.h>
int main(int argc, char **argv)
{
BIGNUM *fat;
char *resp = NULL;
fat = BN_new();
BN_generate_prime(fat, 80, 1, NULL, NULL, NULL, NULL);
resp = BN_bn2dec(fat);
printf("Big Random Value: %s\n", resp);
}
;)
You will have to deal with a string for saving your number.
Because the signed long long min is -9223372036854775808 and max is 9223372036854775807.
1589745896214758962147852 is much more long.
Your problem is ill defined (at time of writing).
If you need exactly 25 digits then you can simply iterate 25 times getting a random number from 0 to 9 and compiling them into a string of digit characters.
If it must be a 25 digit number (i.e. 1025 <= r <= 1026-1) rather than 25 random digits then the first digit must >= 1 (no leading zeroes).
If you require these digits to represent an integer value, upon which you may perform arithmetic operations, rather than a string of digits, then you will be out of luck with C's built-in data types on any likely platform since the value will require at least 85 bits (1025/log(2)).
You can build a 85 bit representation by concatenating the bits returned from a standard random number generator into a byte array If using the standard C library rand() function check your implementation's RAND_MAX value; some implementations only generate 16 bits, so some care is needed to concatenate them since it may not be a whole word of random bits. However to arithmetically manipulate such a number you will have to create arithmetic functions to do that too (or use a "bignum" library).
of size 5, that I want to add, according to some conditions that I will impose. Both strings are in the format 00:00. The first string (s1) represents a certain time of departure of a plane, the second one, is how delayed that departure will be...
This is supposed to be done on a 24h clock.
Let's say, for example
s1=10:45
s1=01:50
so first I have to add the 5 and the 0, see if there's a carry out and if the result is under 9, then add the 4 and the 5, see if the result is under 6. If it isn't I subtract 6 to the addition and add the carry out (1) to the 0 and the 1, then I'll add 1 to 0.
5+0=5
4+5=9 9-6=3 carry out:1
0+1+1=2
0+1=1
12:35
What I would like to obtain is s1=12:35
I don't really get how pointers work... I've tried to understand them, but it was in vain...
Can you help me?
I have some ideas that I will post here:
#include <stdio.h>
#include <string.h>
char*add_hours(char s1[], char s2[])
int i;
for(i=4; i>3; i--){
if(s1[i]+s2[i]>9){
strcpy(s1[i], ((s1[i]+s2[i])-10);
strcpy(s1[i-1], (s1[i-1]+1));
}
...
}
the code goes on for a little while, but it repeats itself a few times. So I didn't think I needed to copy it all here. The problem is, he keeps telling me showing this warning:
"warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast
/usr/include/string.h:128: note: expected 'const char * _restrict_' but argument if of type 'int'
And the same thing for the second argument, for every strcpy there is... I understand the error (I think) but I don't know how to correct it...
I may be wrong, but I think you don't want to add like that.
What happens if you have a depature at 00:30 and an arrival at 04:00, but daylight savings happens inbetween?
Populate a time_t structure. Convert that to a time_t. Add your delay, in seconds. Convert that back to a time_t. Print that out using strftme(). Let the time code in the C library deal with all these issues.
First, you should remove the for loop. It just makes 2 iterations and it is confusing.
Then, the first line of your function should be
char * sum = new char[5];
since you probably want to return a new string. It will also make things clearer.
Try to decompose things in order to simplify your problem. Start writing:
int minutes(char * s);
int hours(char * s);
That respectively return the number of minutes and hours expressed in a string.
strcpy expects strings (array of char/char pointer) as its parameters. What you are giving it are single characters. If you want to modify single characters that way, there is no need to use strcpy.
#include <stdio.h>
#include <string.h>
char*add_hours(char s1[], char s2[])
int i;
for(i=4; i>3; i--){
if(s1[i]+s2[i]>9){
s1[i] = (s1[i]+s2[i])-10;
s1[i-1] = s1[i-1]+1;
}
...
}
There are other logical problems with the code, but this should get you started.
#include <stdlib.h>
#include <string.h>
const int MINS_IN_HR = 60;
int StrToMins(char* str)
{
int res = 0;
char temp[3];
temp[2] = '\0';
memcpy(temp, str, 2);
res += atoi(temp)*MINS_IN_HR;
memcpy(temp, str+3, 2);
res += atoi(temp);
return res;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* s1="10:45", *s2="01:50";
int totalMins = StrToMins(s1) + StrToMins(s2);
printf("%d:%d", totalMins / MINS_IN_HR, totalMins % MINS_IN_HR);
return 0;
}