I'm asking you to know how to convert a constant char variable[] to a unsigned long variable!
The problem doesn't exist if not for :
I've to convert this value for example "0x20DF10EF" if I convert it to long it return me back "551489775".
What i want is to receive back "0x20DF10EF"!
Hope i've explained well enough my problem!
Best regards D.Tibe!
---- Edit ----
while(O != 'I'){
if(reciver.decode(&results)){
CMD[i] = "0x" + String(results.value, HEX);
CMD[i].toUpperCase();
Val[0] = CMD[i].c_str();
//Vil[0] = CMD[i].c_str();
//for(int i = 0; i < sizeof(Val[0])-1 ;i++)
//{
//}
Byte = String(results.bits, DEC);
delay(1000);
O = 'I';
reciver.resume();
}
This is my code!
I have to convert my Val[0] (that is a Constant char) to Unsigned long variable.
Like said before i'll have a value like this 0x20DF10EF in my constant char and i want to get exactly the same on my unsigned long variable, SO :
Val[0] will be = to 0x20DF10EF and i want to get back the same value but into the unsigned long variable like this
unsigned long Var will be = to 0x20DF10EF
If I understood correctly, you want to parse a const char * string with an hex number and put it into a variable.
If this is correct, there are two ways: using the sscanf function or converting it by hand.
Method 1:
unsigned long result;
if (sscanf(Val[0], "0x%x", &result) != 1)
{
Serial.println("Val[0] is not a valid hex value");
}
Method 2:
unsigned long result = 0;
byte i;
for (i = 2; i < strlen(Val[0]); i++)
{
if ((Val[0][i] >= '0') && (Val[0][i] <= '9'))
{
result = (result << 4) + Val[0][i] - '0';
}
else if ((Val[0][i] >= 'A') && (Val[0][i] <= 'F'))
{
result = (result << 4) + 10 + Val[0][i] - 'A';
}
else if ((Val[0][i] >= 'a') && (Val[0][i] <= 'f'))
{
result = (result << 4) + 10 + Val[0][i] - 'a';
}
else
{
Serial.println("Val[0] is not a valid hex value");
break;
}
}
By the way, adding 0x in front of the string is useless for this conversion. If you can, remove it and then replace "0x%x" with "%x" in the sscanf solution, or i = 2 with i = 0 in the hand-made one.
Related
As I know, it is easy to convert single byte to signed decimal by
char source_binary = '\xff' //-1
int signedInt = (int)source_binary //signedInt = -1
But I would like to know if any better way to handle in multiple byte
//Example -2, represent as 0xFFFE. I got two byte as follow:
char highByte = '\xff'
char lowByte = '\xfe'
Here is my solution:
- (int) convertTwoBytesBinaryToSignedInt:(char)highByte :(char)lowByte
{
int retValue = 0;
int hiValue = (int) highByte;
int loValue = 0;
if ((int)lowByte < 0)
loValue = 0 - ((lowByte ^ '\xff') + 1);
else
loValue = 0 - 256 + (int)lowByte;
if (hiValue < 0) {
//Negative Binary
retValue = (((hiValue+1)*256)+ loValue);
} else {
//Postive Binary
retValue = ((int)highByte)*256+(int)lowByte;
}
return retValue;
}
Would you please advise me any better way to convert it to signed decimal?
int word = ((int) highByte << 8) | (unsigned char) lowByte;
EDIT: insufficient testing. :)
I am trying to write a program that will take an integer input, and then convert it to words. for example: 123, one two three. Also -3908, negative three nine zero eight.
My code works 90% of the time, the only issue coming along when i am putting one or more zeros on the end of the integer. eg. 70800 will come up as seven zero eight. It completely misses the end zeros. I understand why that is happening but does anybody know if there is a way around it.
PS(i am not allowed as a part of this task to accept the input as a string and split it into an array, so it would be best if the answer is based off this code).
int main(int argc, const char * argv[])
{
#autoreleasepool {
float abNumber;
int i = 0;
float number;
float result;
float firstNumber;
printf("type a number: ");
scanf("%f", &firstNumber);
abNumber = abs(firstNumber);
if (firstNumber < 0) {
printf("negative ");
}
number = abNumber;
while (number >= 10) {
number = number / 10;
i++;
}
do {
float countNumber = abNumber;
float power = powf(10, -i);
float powerNo2 = powf(10, i);
countNumber = countNumber * power;
result = floorf(countNumber);
if (result == 9){
printf("nine ");
}
if (result == 8){
printf("eight ");
}
if (result == 7){
printf("seven ");
}
if (result == 6){
printf("six ");
}
if (result == 5){
printf("five ");
}
if (result == 4){
printf("four ");
}
if (result == 3){
printf("three ");
}
if (result == 2){
printf("two ");
}
if (result == 1){
printf("one ");
}
if (result == 0){
printf("zero ");
}
while (abNumber > powerNo2) {
abNumber = abNumber - powerNo2;
}
i--;
} while (i >= 0);
}
return 0;
}
The main error seems to be that
while (abNumber > powerNo2) {
should be
while (abNumber >= powerNo2) {
But I would recommend not to use floating point arithmetic at all, to avoid
possible rounding errors. The same can be achieved with simple integer arithmetic
(I have omitted the "negative case" for simplicity):
int number;
printf("type a number: ");
scanf("%d", &number);
// Determine highest power of 10 that is <= the given number:
int power = 1;
while (10 * power <= number) {
power *= 10;
}
// Extract each digit:
while (power > 0) {
int digit = (number / power) % 10;
/*
* Use switch/case to print 'digit' as a string ...
*/
power /= 10;
}
I would go for recursive solution, like that
int print(int num)
{
if( num )
{
int mod = num%10;
print(num/10);
switch(mod)
{
case 0:printf(" zero");break;
case 1:printf(" one");break;
case 2:printf(" two");break;
case 3:printf(" three");break;
}
}
return 0;
}
Recursivy divide the number untill nothing left of it, on the way back print the mod.
Why don't you just input the number as a string then loop through each character:
Exemple: http://ideone.com/E8QspN
Input:
-12003200
Output:
negative one two zero zero tree two zero zero
Code:
#include <stdio.h>
int main(int argc, char *argv[])
{
char input[25];
scanf("%s", input);
int i = 0;
while (input[i] != '\0') {
switch(input[i]) {
case '-' :
printf("negative");
break;
case '0' :
printf("zero");
break;
case '1' :
printf("one");
break;
case '2' :
printf("two");
break;
case '3' :
printf("tree");
break;
case '4' :
printf("four");
break;
case '5' :
printf("five");
break;
case '6' :
printf("six");
break;
case '7' :
printf("seven");
break;
case '8' :
printf("eight");
break;
case '9' :
printf("nine");
break;
default :
break;
}
printf(" ");
i++;
}
return 0;
}
Consider the following:
Code
#include <stdio.h>
#include <stdlib.h>
const char *numbers[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
void printNum(int num);
int main(void)
{
int num;
printf("Enter a number: ");
scanf("%u", &num);
printNum(num);
printf("\n");
return 0;
}
void printNum(int num)
{
int absNum = abs(num);
if(absNum > 9)
printNum(num / 10);
if((absNum < 10) && (num < 0))
printf("negative");
printf(" %s", numbers[absNum % 10]);
}
Example Output
Enter a number: 2582
two five eight two
Enter a number: -943
negative nine four three
Enter a number: 1000
one zero zero zero
Enter a number: -1000
negative one zero zero zero
Logic
Get an integer from user.
Send to recursive function.
Keep recursing until the least significant digit is left. This is to print in the correct order.
Print digit as a string by using a lookup table.
Keep someone a high five.
To Do
Error checking
hi i am working on arm controller lm3s8962 i m not able to understand the code below as per my understanding it is checking if the character is from the array or not, which he created using the ascii characters{i.e in the while loop : while(*pcStr != 0) },
i am not able to get what he is doing in the code after the line "Build and display the character buffer" plz can anyone explain this
void
RIT128x96x4StringDraw(const char *pcStr, unsigned long ulX,
unsigned long ulY, unsigned char ucLevel)
{
unsigned long ulIdx1, ulIdx2;
unsigned char ucTemp;
//
// Check the arguments.
//
ASSERT(ulX < 128);
ASSERT((ulX & 1) == 0);
ASSERT(ulY < 96);
ASSERT(ucLevel < 16);
//
// Setup a window starting at the specified column and row, ending
// at the right edge of the display and 8 rows down (single character row).
//
g_pucBuffer[0] = 0x15;
g_pucBuffer[1] = ulX / 2;
g_pucBuffer[2] = 63;
RITWriteCommand(g_pucBuffer, 3);
g_pucBuffer[0] = 0x75;
g_pucBuffer[1] = ulY;
g_pucBuffer[2] = ulY + 7;
RITWriteCommand(g_pucBuffer, 3);
RITWriteCommand(g_pucRIT128x96x4VerticalInc,
sizeof(g_pucRIT128x96x4VerticalInc));
//
// Loop while there are more characters in the string.
//
while(*pcStr != 0)
{
//
// Get a working copy of the current character and convert to an
// index into the character bit-map array.
//
ucTemp = *pcStr++ & 0x7f;
if(ucTemp < ' ')
{
ucTemp = 0;
}
else
{
ucTemp -= ' ';
}
//
// Build and display the character buffer.
//
for(ulIdx1 = 0; ulIdx1 < 6; ulIdx1 += 2)
{
//
// Convert two columns of 1-bit font data into a single data
// byte column of 4-bit font data.
//
for(ulIdx2 = 0; ulIdx2 < 8; ulIdx2++)
{
g_pucBuffer[ulIdx2] = 0;
if(g_pucFont[ucTemp][ulIdx1] & (1 << ulIdx2))
{
g_pucBuffer[ulIdx2] = (ucLevel << 4) & 0xf0;
}
if((ulIdx1 < 4) &&
(g_pucFont[ucTemp][ulIdx1 + 1] & (1 << ulIdx2)))
{
g_pucBuffer[ulIdx2] |= (ucLevel << 0) & 0x0f;
}
}
//
// Send this byte column to the display.
//
RITWriteData(g_pucBuffer, 8);
ulX += 2;
//
// Return if the right side of the display has been reached.
//
if(ulX == 128)
{
return;
}
}
}
}
He is doing some bit manipulations to build up bytes.
x |= y is the same as x = x | y, which keeps all the 1s in x and also changes some of the 0s to 1 if y has a 1 in the same position.
1 << i is a byte with a single 1 bit in the ith position from the right.
x = y & 0xf0 copies only the left 4 bits of y into x.
So he is looking up values in an array, checking particular bits of those values, then filling up another array with number created from those bits. You will have to work out the particulars for yourself.
i am trying to increment ipv6 address based on mask.
i am getting problem when there is F in place of increment.
could any one plz check this
public String IncrementIPV6ForPrefixLength (String IPv6String, int times) throws UnknownHostException
{
int result , carry = 0, i;
int bits;
int mask=0;
int index=IPv6String.indexOf("/");
mask=Integer.parseInt(IPv6String.substring(index+1, IPv6String.length()));
IPv6String=IPv6String.substring(0, index);
InetAddress iaddr=InetAddress.getByName(IPv6String);
byte[] IPv6Arr=iaddr.getAddress();
if(mask > 128 || mask < 0)
return null;
i = mask/8;
bits = mask%8;
if(bits>0)
{
result = ((int)(IPv6Arr[i]>>(8-bits))) + times;
IPv6Arr[i] =(byte) ((result << (8-bits)) | (IPv6Arr[i] & (0xff >> (bits))));
carry = (result << (8-bits))/256;
times /= 256;
}
i--;
for(;i>=0;i--)
{
result = ((int)IPv6Arr[i]) + ((times + carry)& 0xFF);
IPv6Arr[i] = (byte)(result % 256);
carry = result / 256;
if(carry == 0)
{
iaddr=InetAddress.getByAddress(IPv6Arr);
String s=iaddr.toString();
if(s.indexOf('/') != -1){
s = s.substring(1, s.length()).toUpperCase();
}
StringBuffer buff =new StringBuffer("");
String[] ss = s.split(":");
for(int k=0;k<ss.length;k++){
int Differ = 4 - ss[k].length();
for(int j = 0; j<Differ;j++){
buff.append("0");
}
buff.append(ss[k]);
if(k!=7)buff=buff.append(":");
}
return buff.toString()+"/"+mask;
}
times /= 256;
}
return null;
}
input like this:
FD34:4FB7:FFFF:A13F:1325:2252:1525:325F/48
FD34:41B7:FFFF::/48
FD34:4FBF:F400:A13E:1325:2252:1525:3256/35
output like this
if increment by 1
FD34:4FB8:0000:A13F:1325:2252:1525:325F/48
FD34:41B8:0000::/48
FD34:4FC0:0400:A13E:1325:2252:1525:3256/35
if increment by 2
FD34:4FB8:0001:A13F:1325:2252:1525:325F/48
FD34:41B8:0001::/48
FD34:4FC0:1400:A13E:1325:2252:1525:3256/35
can u plz find where i am doing wrong.
Disregarding the posted code, try to model the operation as a direct numerical operation on the 128-bit number that the IPv6 address really is. Convert to BigInteger and use BigInteger.add.
I'm very new to Arduino and C programming.
I'm making a GPS speedo and I'm trying to read in some serial, store a value from a substring and echo it back via serial.
At the moment I'm having problems storing the substring.
I've gotten to the point where I'm able to get some data between < and >.
But the data doesn't come in like that. It's a NMEA data stream and the data I want is between ,N, and ,K,.
So I've been trying to replace ,N, with < and ,K, with > .
Just can't get it to work. I get error: request for member 'replace' in 'c', which is of non-class type 'char'
Here's my code so far....
int indata = 0;
int scrubdata = 0;
char inString[32];
int stringPos = 0;
boolean startRead = false; // is reading?
void setup() {
Serial.begin(4800);
}
void loop() {
String pageValue = readPage();
Serial.print(pageValue);
}
String readPage(){
//read the page, and capture & return everything between '<' and '>'
stringPos = 0;
memset( &inString, 0, 32 ); //clear inString memory
while(true){
if (Serial.available() > 0) {
char c = Serial.read();
c.replace(",N,", "<");
c.replace(",K,", ">");
if (c == '<' ) { //'<' is our begining character
startRead = true; //Ready to start reading the part
}
else if(startRead){
if(c != '>'){ //'>' is our ending character
inString[stringPos] = c;
stringPos ++;
}
else{
//got what we need here! We can disconnect now
startRead = false;
return inString;
}
}
}
}
}
By Default:
Serial.read() returns an int if you must process the data this way, try casting it to char with:
char c = (char) Serial.read();
Another way to do this:
Would be to seek your beginning string (discarding un-needed data) using Serial.find() then reading data until you met your end character ",K," with Serial.readBytesUntil()
Something like this would work quite well:
char inData[64]; //adjust for your data size
Serial.setTimeout(2000); //Defaults to 1000 msecs set if necessary
Serial.find(",N,"); //Start of Data
int bRead = Serial.readBytesUntil(",K,", inData, 64); //Read until end of data
inData[bRead] = 0x00; //Zero terminate if using this as a string
return inData;