Decimal to binary

Hi,
I have a question, maybe someone know how to do, i having a decimal number in a variable, and this three digits, i need to convert to binary, and actually put it on a port. Lets say for example decimal number 258. And get it out as parallel binary on lets say portB.
Any hints on how to do?

just

byte x = 258; // EDIT:  see @UKHelibob remark in post 3 though
portRegister = x;

the variable does not hold decimal data, it's all binary , it's just a representation.

258 wont fit in 8 bits and PORTB is only 8 bits wide, so you have a problem straight away

Would you like to try a different example ?

1 Like

good point !

You have said that you will be changing your glasses and it is not yet changed :smiley:!

I actually had my glasses on and missed it.. Need a new brain, not glasses :slight_smile:

1 Like

Is compression allowed?

Only if you can demonstrate how it would work

2 Likes

What do you mean by a decimal number? Numbers are all stored as binary, they are just displayed as decimal because that's how humans usually want to see them.

int x= 258;
PORTB=x & 0xFF; // everything over 255 will be lost and serial port will be disturbed

do you understand how binary values work, that each bit represents a power of 2, that 258 is 1 0000 0010?

by decimal, do you mean integer above, or could you possibly mean a value with fractional bits?

258 == 0x102 == 0b100000010

the low 8 bits holds 2, not 255. 8 bits can't hold 256, can hold 0 to 255.

I don’t think that the @kolaha meant that the lower 8 bits would be 255.
As I see, he wrote about something completely different.

Ha ha, my misstake, i just took a number, im thinking about following, i want to convert a CB radio to 29 MHz ham radio. But i need frequency split, and data from channel selector is 8 bit paralell. So i was thinking, if put a Mega in between, read 8 bit, mirror it out, but if a control pin goes high, i reduce the data by 10. Then its 100KHz.

so what you really want to do? digital frequency synthesizer?

You don't need the & 0xFF. The C++ standards says that you'll get the LSB in PORTB

Before the advent of Computer, there were decimal numbers which were represented using the combinations of digits: 0, 1, 2, 3, 4, 5, 7, 8, and 9. For example: 4567. I want save it exactly as it is in the memory system of ATmega328P MCU; what will be the declaration?

i know, but if it not written someone may think entire variable will send to this port.

it's still true after the "advent of computer" :wink:

it could be char number[] = {'4','5','6','7'};

I, II, III, IV, V, VI, VII, VIII... For example: MMMMDLXVII

2 Likes