カラーコードを表示するプログラムを作りました。期待どおりに動作しましたが、一部の環境では同じ表示にならないかもしれません。

どのように修正すれば環境への依存性を低くできるか、分かりますか?
main.c
#include <stdlib.h>
#include <stdio.h>
unsigned int MakeColor(unsigned char nRed, unsigned char nGreen, unsigned char nBlue) {
unsigned int r = (unsigned int)nRed << 16;
unsigned int g = (unsigned int)nGreen << 8;
unsigned int b = (unsigned int)nBlue;
return r | g | b;
}
int main(void) {
printf("red = #%06x\n", MakeColor(255, 0, 0));
printf("blue = #%06x\n", MakeColor(0, 0, 255));
printf("magenta = #%06x\n", MakeColor(255, 0, 255));
return EXIT_SUCCESS;
}
期待される実行結果
red = #ff0000
blue = #0000ff
magenta = #ff00ff

カラーコードっていうのは分かるかしら?

はい。HTMLとかCSSで使うやつですよね。「黄色」は「#ffff00」とかの。

そうそう。そのカラーコードを「赤・緑・青」の三原色から計算するプログラムね。

三原色はそれぞれ0〜255の範囲で指定するから、
unsigned char
なんですね。

そういうこと。

で、計算した結果が
unsigned int
になる、と。

だいたいの場合はこれで問題ないのだけれど。

一部の環境ではちゃんと動かないんですね。でも、なんで……。

期待どおりの計算が成立するための前提条件を考えてみましょう。