0

I'm a beginner in C language, I was wondering how I store an unsigned short into a char array?

unit16_t is unsigned short, and below is my code.

uint16_t  combined = 1234;
char echoPrompt[] = {combined};

EDIT:

Sorry for being unclear I need echoPrompt to be a char array and combined needs to be an integer. I am passing echPrompt as a char array to a UART_write which required a char array.

Johnathan Logan
  • 357
  • 5
  • 14

2 Answers2

2

You cannot pass an array to a function. You can pass a pointer. Pointers are not arrays.

If your UART_write looks anything like any of the standard C/POSIX functions write, fwrite etc, you need

  result = UART_write (..., 
        (char*)&combined, 
        sizeof(combined), ...);

There is no need in a char array.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
1

if I understood correctly, you want to save each upper and lower 1 byte of short in char array.

well, why don't you just use union?

typedef struct uint16_s{ 
    char upper; 
    char lower;
} uint16_s;

typedef union uint16_u{
    uint16_s sBuf;
    uint16_t tBuf;
} uint16_u;

uint16_u combined;
combined.tBuf = 1234;
char echoPrompt[] = {combined.sBuf.upper, combined.sBuf.lower};
Jang Whe-moon
  • 125
  • 1
  • 9