C/C++ integer to hex to char array to char - c++

Well I have been trying to convert this integer into hex and have successfully done so but I need to use this hex for setting something. Now for this I need to use a char not a char array. Nothing else has worked without manually setting it. Maybe the problem lies in the issue that I use sprintf for the conversion to hex but either way I am sure there is a way to complete this task. Now What I need to change is have the output be char z but I haven't found a way to get this to work. Any help is greatly appreciated. Thanks
EDIT: now thi code may not make sense directly because it is incomplete and I saw no purpose inputting unrelated code. int x will never be over 100 and the whole point is to convert this into a hex and write it to the memory of a setting I have. So I have been trying to figure out how to convert the integer into hex into a char. nonstring as someone pointed out even though sprintf converts it to a string stored in a char as I just noticed. But I need to take the int convert to hex and assign that to a char variable forbuse later on. And that is where I am stuck. I do not know the best way to go about completely all that in a format and way without going into a string and other things.
VOID WriteSetting(int x)
{
char output[8];
sprintf(output, "0x%X", x);
char z = 0x46
unsigned char y = z
}
Working Code:
VOID WriteSetting(int x)
{
unsigned char y = (unsigned char)x;
Settingdb.Subset.Set = y;
}

If what you want is for:
WriteSetting(70);
or
WriteSetting(0x46);
to do the same thing as
char z = 0x46;
unsigned char y = z;
then all you need to do is:
void WriteSetting(int x)
{
unsigned char y = x;
}
Integers don't have any inherent base - they're just numbers. There's no difference at all between unsigned char y = 0x46; and unsigned char y = 70;.

Have you tried
printf("0x%X", z);

While the C++ standards do not explicitly require it, the size of a character is sometimes a byte, and an integer 4 bytes. I presume that this is why you are using an array of 4 characters.
So when you have an integer type and try to cram it into a single character, you'll lose precision.
P.S. A more precise explanation of sizes of data types is here: What does the C++ standard state the size of int, long type to be?

void WriteSetting(unsigned char *y, int x){
if(x > 100){
fprintf(stderr, "x value(%d) is invalid at %s\n", x, __func__);
return ;
}
*y = x;//There is no need for conversion probably
}

Related

How can i get the char by having the value of that char in the ascii table?

I've been trying for a long time, searching a lot online, but I can't find anything about it...
I have an integer given by a function. This integer is the value of a char in the ascii table and I want to know what char it is. I've tried functions like toascii() or _itoa(), but none of these seems the right one...
Can you tell me what function should I use and with what parameteres?
Thanks.
It's very easy, no function needed, just assign it. In C++ chars are integers.
int char_value = ...;
char actual_char = char_value;
cout << actual_char << '\n';
You might add a cast to that assignment but it's not strictly necessary.
This integer is the value of a char in the ascii table and I want to know what char it is
you do not need any function
char theChar = (char) theNumber;
or better
char theChar = static_cast<char>(theNumber);
Thanks guys, I fixed it on my own, I don't know why but my IDE didn't let me do something like char CharVar = IntVar. Now somehow I fixed it and it works properly.

Convert char* to uint8_t

I transfer message trough a CAN protocol.
To do so, the CAN message needs data of uint8_t type. So I need to convert my char* to uint8_t. With my research on this site, I produce this code :
char* bufferSlidePressure = ui->canDataModifiableTableWidget->item(6,3)->text().toUtf8().data();//My char*
/* Conversion */
uint8_t slidePressure [8];
sscanf(bufferSlidePressure,"%c",
&slidePressure[0]);
As you may see, my char* must fit in sliderPressure[0].
My problem is that even if I have no error during compilation, the data in slidePressure are totally incorrect. Indeed, I test it with a char* = 0 and I 've got unknow characters ... So I think the problem must come from conversion.
My datas can be Bool, Uchar, Ushort and float.
Thanks for your help.
Is your string an integer? E.g. char* bufferSlidePressure = "123";?
If so, I would simply do:
uint8_t slidePressure = (uint8_t)atoi(bufferSlidePressure);
Or, if you need to put it in an array:
slidePressure[0] = (uint8_t)atoi(bufferSlidePressure);
Edit: Following your comment, if your data could be anything, I guess you would have to copy it into the buffer of the new data type. E.g. something like:
/* in case you'd expect a float*/
float slidePressure;
memcpy(&slidePressure, bufferSlidePressure, sizeof(float));
/* in case you'd expect a bool*/
bool isSlidePressure;
memcpy(&isSlidePressure, bufferSlidePressure, sizeof(bool));
/*same thing for uint8_t, etc */
/* in case you'd expect char buffer, just a byte to byte copy */
char * slidePressure = new char[ size ]; // or a stack buffer
memcpy(slidePressure, (const char*)bufferSlidePressure, size ); // no sizeof, since sizeof(char)=1
uint8_t is 8 bits of memory, and can store values from 0 to 255
char is probably 8 bits of memory
char * is probably 32 or 64 bits of memory containing the address of a different place in memory in which there is a char
First, make sure you don't try to put the memory address (the char *) into the uint8 - put what it points to in:
char from;
char * pfrom = &from;
uint8_t to;
to = *pfrom;
Then work out what you are really trying to do ... because this isn't quite making sense. For example, a float is probably 32 or 64 bits of memory. If you think there is a float somewhere in your char * data you have a lot of explaining to do before we can help :/
char * is a pointer, not a single character. It is possible that it points to the character you want.
uint8_t is unsigned but on most systems will be the same size as a char and you can simply cast the value.
You may need to manage the memory and lifetime of what your function returns. This could be done with vector< unsigned char> as the return type of your function rather than char *, especially if toUtf8() has to create the memory for the data.
Your question is totally ambiguous.
ui->canDataModifiableTableWidget->item(6,3)->text().toUtf8().data();
That is a lot of cascading calls. We have no idea what any of them do and whether they are yours or not. It looks dangerous.
More safe example in C++ way
char* bufferSlidePressure = "123";
std::string buffer(bufferSlidePressure);
std::stringstream stream;
stream << str;
int n = 0;
// convert to int
if (!(stream >> n)){
//could not convert
}
Also, if boost is availabe
int n = boost::lexical_cast<int>( str )

how can i assign float value to char* c[] array

I have string,int,float values and trying to assign those values to char* c[] array like this.
char *str = "helloo";
int int = 1000;
short st1[]={32760};
float flt = 2.345;
char* c [] = {(char*)int1,(char*)str,(char*)flt,(char*)st1};
but for float getting illegal explicit conversion from 'float' to 'char * '
anybody tel me how to assign?
You can't just cast those types and expect to get useful results. Casting is a minimal operation which can work to transform data in certain predefined ways, but it won't (for example) intelligently turn integers into their string representations.
That's why your compiler is complaining.
If you want the string representation of numeric data, you have to convert them differently, with something like:
char intStr[30]
sprintf (intStr, "%d", int1);
If you're looking to get string representations of them all, you can do something like:
char *str = "helloo";
int int1 = 1000;
short st1[]={32760};
float flt = 2.345;
char mybuff1[50], mybuff2[50], mybuff3[50], mybuff4[50];
sprintf (mybuff1, "%d", int1);
sprintf (mybuff2, "%s", str);
sprintf (mybuff3, "%f", flt);
sprintf (mybuff4, "%d", st1[0]);
char *c [] = {mybuff1, mybuff2, mybuff3, mybuff4);
And be aware that, although C and C++ have very similar idioms, and are mostly compatible if you stick to a subset, they are not the same language and the best way to do something changes dramatically depending on the actual language you're using.
For example, it's rarely necessary to use C-style strings in C++ since that language provides an impressive real string type. Ditto for malloc/free as opposed to new/delete and many other aspects.
Questions should generally be tagged C or C++, rarely both.
In C++:
#include <string>
std::string arr[] = { std::to_string(1000),
"helloo",
std::to_string(2.345f),
std::to_string(32760) };
You can use arr[0].c_str() etc. to get back char const *s.

For loop writing special signs

void printchars()
{
for (x=128;x<224;x++)
write(x);
I want the x to be a char in the write function. How can i change the x to be treated by the write functions as a char, but an int in the loop?
What is the point of making x an int if you're just going to strip away its range? That's what makes this a very strange request. You should just make x a unsigned char -- for(unsigned char x = 128; x <224; ++ x) { ....
If you just want to ensure you're calling the unsigned char template specialization of write<>, then call it like this:
write<unsigned char>(x);
If not, then you will have to use type casting:
write((unsigned char)x);
Edit: I just realized what you might be experiencing. My guess is that you originally used char but found something wrong with numbers over 127. You should probably be using unsigned char for x instead of either int or char. I edited my answer to accommodate this. char has a range of -128 to +127. unsigned char has a range of 0-255.
Cast x to a char:
write(static_cast<char>(x));
Note that it is ok for x to be a char as the loop counter as well.

How to set a character in C++?

This is probably very obvious, in fact so obvious that no C++ reference I could find online cares to document it.
I need to know how to set the byte value of a char in C/C++. For example, if I want the byte value 233 in the char, how do I do?
Yes, it is too obvious:
char x = 233;
A char is a 1byte int. So you can set the value in the same way as you would an int.
char c = 123;
char d = 0x12;
etc...
char x = 233;
Yea, literally as simple as that.